FAQ Database Discussion Community


Defining mathematical operator for classes

php,operator-overloading,php-5.6
Is (mathematical) operator overloading possible for PHP objects just like Python? I think the answer is no since I searched a lot and found nothing. Just want to confirm. I have defined classes for (vectors) points and I want them to add up like numbers (their corresponding coordinates) and also...

When should I return pointer to object (not an object) from the operator function?

c++,operator-overloading,return-type
This is a follow up question to this. I understood that it returning pointer to object can result memory leak, also because of raw pointers they are error prone, also tricky. So,number of peoples advised me to not return pointer to an object from operator function. So,I am convinced to...

What is the syntax for Operator Overloading in C++?

c++,class,operator-overloading,overloading
I was studying C++, and when I made a little program to learn more about Operator Overloading the program gives an erro in the main function where I wrote "Ponto p1(1,5), p2(3,4), Soma;". Can anyone explain me how to use Operator Overloagin correctly? Thank you. PS: The program is in...

Haskell Polymorphism

haskell,polymorphism,operator-overloading
data Set a = Set [a] -- Example 1 instance (Eq a, Ord a) => Eq (Set a) where (Set xs) == (Set ys) = (sort xs) == (sort ys) -- Example 2 instance (Eq a, Ord a) => Eq (Set a) where (==) = eqSet eqSet (Set xs) (Set...

C++ Trouble overloading operators in a template class

c++,templates,operator-overloading
Every time I add comments inside the definitions of the operators, it starts giving me errors, but removing the comments immediately gets rid of the errors. I don't see why comments would have any effect at all on the code. Also just general advice on the overloading of operators in...

Error C2679: binary '<<' : no operator found (vector iterators used)

c++,operator-overloading,operator-keyword,cout,ostream
The full error message reads: Error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::_Vector_iterator< std ::_Vector_val < std::_ Simple _ types < projects > > >' (or there is no acceptable conversion) Not the prettiest but here's my code up to the error,...

std::find on vector of objects with overloaded == operator

c++,operator-overloading
I am trying to use std::find on the following vector: std::vector<LoopDetectorData *> Vec_loopDetectors; And this is how I am using it: const LoopDetectorData *searchFor = new LoopDetectorData( (*it).c_str(), "", vehicleName.c_str() ); std::vector<LoopDetectorData *>::iterator counter = std::find(Vec_loopDetectors.begin(), Vec_loopDetectors.end(), searchFor); This is the definition of LoopDetectorData class with operator == overloading. class...

Invoking overload constructor within constructor

c++,constructor,operator-overloading
I was wondering either it is possible in c++ to run a constructor overload within another constructor. I know it is possible using regular methods. What I am tryng to do: class Foo { public: Foo(); Foo(int val); }; Foo::Foo() { Foo(1); } Foo:Foo(int val) { std::cout << val; }...

F# Custom operators

f#,operator-overloading
I've defined a custom operator in F# like this: static member (&?) value defaultValue = if value = null then defaultValue else value The operator is defined within a type and should be called in the following scenario: I'm retrieving information about the system processors using WMI. Now i want...

Child calls to parent which calls back to child … or not

python,inheritance,operator-overloading,python-datetime
from datetime import timedelta class A: def __abs__(self): return -self class B1(A): def __neg__(self): return 'neg from B1' class B2(timedelta): def __neg__(self): return 'neg from B2' print(abs(B1())) # neg from B1 print(abs(B2(-1))) # 1 day, 0:00:00 Why does the first print call use the overridden method, but the second one...

Overloaded [] operator and referring to the object itself

c++,operator-overloading
I need to refer to each vertex in a method inside the body of class. I've tried using this->, Solid:: etc. but that didn't come up well either. Anyway I've got everything other overloaded but I can't figure it out nor search it anywhere in the net. #define VERTICES_NR 8...

best way to create an operator+ inside a class without declaring so many unnecessary variables

c++,c++11,operator-overloading,operators
So we were given a question where we have a class called Cocktail with name and volume attributes. Now they want us to "write an overloading operator addition to make the mix of two cocktails i.e. add two cocktails together which gives : volume of cocktail 1 + volume of...

Is changing inherited variable name is still considred as override?

php,oop,inheritance,operator-overloading,override
As ask above I have a function with one input parameter in base class. Does overriding it in derived class but with change of the variable name still considered as override and not as overload? I know it is the case for languages such as Java, but what about php?...

How do i use this unique operator overloaded function

c++,operator-overloading
I came across this operator overload during my use of the sqlapi which does exactly what i need, but i'm not sure how it works. sqlapi.h class SQLAPI_API SAString { public: //stuff //! Return pointer to const string operator const SAChar *() const; //stuff } The only way that i...

No viable conversion from std::function to bool

c++,c++11,operator-overloading,implicit-conversion
The C++11 std::function is supposed to implement operator bool() const, so why does clang tell me there is no viable conversion? #include <functional> #include <cstdio> inline double the_answer() { return 42.0; } int main() { std::function<double()> f; bool yes = (f = the_answer); if (yes) printf("The answer is %.2f\n",f()); }...

How to overload the ostream operator for 3D vector?

c++,vector,operator-overloading
How to overload the stream extraction operator for a three dimensional vector? vector<vector<vector<int>>> V(5, vector<int>>(3, vector<int>(2))) I came up with the following response. Why isn't the following code correct? template <typename T> ostream& operator<<(ostream &output, vector<T> &V) { for(int i = 0; i < V.size(); i++) for(int j = 0;...

“Merging two files” using operator “+”

c++,file,operator-overloading,concatenation
I was wondering, if it would be possible to code something like this: File1("dataOut.txt")=File2("Data1.txt")+File3("Data2.txt") I believe the thing I seek is to achieve concatenation via operator+. Correct me if I'm wrong, but I would have to overload that operator somewhere? I know it would probably be easier to just copy...

overload resolution fails for derived class

c++,templates,operator-overloading,overloading,overload-resolution
I am using a class mArray, which implements numerical data containers with variable dimensionality template <typename T> class mArray<T>: { ... std::vector<T> my_data; } Another class mImage inherits from mArray and provides image-specific operations, and another class mDcmImage inherits from mImage and provides format-specific functions. I thought this was a...

Templates, no match for 'operator<<' in 'out << “(”'

c++,templates,operator-overloading,manipulators
I'm trying to overload << operator for template and I'm getting this error. What I'm trying to achieve is overloaded operator << that will provide opening bracket, all tab items separeted by "," and closing bracket to 'out'. Here is part of my code: template <typename T> class arry{ T...

C++ Operator “>>” overloading error

c++,file,templates,operator-overloading,istream
I need to overload operator >> to help me read my configuration from a file. This is what i came up with: template<typename T>istream& operator>>(istream &in, const config<T> &w) { in>>w.attribName1; for(int z=0;z<3;z++) { in>>w.attribute1[z]; } in>>w.attribName2; for(int x=0;x<3;x++) { in>>w.attribute2[x]; } in>>w.attribName3; for(int v=0;v<3;v++) { in>>w.attribute3[v]; } in>>w.attribName4; for(int...

Overloading operator<<(ostream&, T) where T is “enum class MyEnum”

c++,c++11,operator-overloading,ostream
I've been trying to overload operator<< so that I can do this with my enum types: /* enum class Color { ... } */ Color color = GetColor(); std::wcout << L"The color is " << color << std::endl; OUTPUT: The color is Green. Here's some test code I'm compiling in...

subscript operator in C++

c++,operator-overloading
is subscript operator [ ] unary or binary operator ? I'm quite new to C++ and was going through operator operloading and wondered is subscript a unary or binary?...

C++ Overloading [] from left and right

c++,string,class,operator-overloading
I'm trying to think how can I overload [] from both left and right to function as set and get for a custom string class I'm working on. for example: char x= objAr[1]; //get objAr[2]='a'; //set The string class basically looks like this: class String { private: char* data; unsigned...

fraction operator overloading

c++,operator-overloading,fractions
I am new in C++ and I have a problem with operator overloading. I just implemented the functions in header file.I want to add two fractional numbers simplest form to each other.I implemented a gcd for simplification and implemented operator + for addinf the together bu I got an error...

c++ object construction using operator=

c++,c++11,constructor,operator-overloading
I am maintaining the rule of three like this -- // actual constructor stuff::stuff(const string &s) { this->s_val = s[0]; this->e_val = s[s.length() - 1]; } // copy constructor stuff::stuff(const stuff &other) { this->s_val = other.s_val ; this->e_val = other.e_val ; } // assignment stuff& stuff::operator=(const stuff &other) { stuff...

Is there a workaround to make class operators work for built-in types

delphi,operator-overloading
I can use class operators for strings using an intermediate holding record. So that I can so implicit conversion of built-in types. program TestNewStringHelper; {$APPTYPE CONSOLE} uses System.SysUtils; type TStringRecord = record private Data: string; public class operator Implicit(const a: TStringRecord): Integer; inline; class operator Implicit(const a: string): TStringRecord; inline;...

Operator overloading: calling friend function from member function

c++,operator-overloading,friend-function
I have a Student class. I want to overload + operator so I can add a double variable to class. Here is Student class: class Student { private: std::string firstName; double grade; public: Student(const std::string &firstName, double grade); double getGrade() const; friend Student operator+(double grade, const Student &student); Student operator+(double...

Why does overloading ostream's operator<< need a reference “&”?

c++,operator-overloading
I've been learning C++. From this page, I understood that overloading "<<" operator of ostream can be done in this way. ostream& operator<<(ostream& out, Objects& obj) { // return out; } //Implementation and friend ostream& operator<<(ostream& out, Object& obj); //In the corresponding header file My question is... why does this...

Overload matrix operator

c++,matrix,operator-overloading
I'm working on matrix multiplication using Strassen algorithm. I'm trying to overload the ' * ' operator without success. I have low experience in C++ and I don't know how to fix it. I got no error at runtime, but the Matrix parameter m has weard values (8215421532 instead of...

How to force operator>>(C) overload to match container?

c++,templates,operator-overloading,containers,extraction-operator
I would like to have operator>>() overloads for any "base" type and for any container type. This is what I have so far: typedef uintmax_t my_t; template <typename T> std::istringstream &operator>>(std::istringstream &iss, T &v) { static my_t um = 6009; v = um++; return iss; } template <template <class> class...

Get the type of & for built-in and operator&()?

c++,templates,operator-overloading,template-meta-programming,addressof
Edit: The answer I've marked below isn't 100% correct, that's actually in a comment: using TPtr = decltype(&std::declval<T&>()); I'm trying to use std::conditional<> to get the type of &T, where T may have operator&(), or not. The simple solution is to not even try, instead specify another template argument: struct...

How to call another member function when operator overloading (C++)

c++,operator-overloading
How would I use a member function (in this case, magnitude()) within my definition for the function overload of the greater than operator >? The operator should compare the magnitudes of two objects of the classVector2D from which magnitude() is also a member. I receive the following: error C2662: 'double...

vector/array bounds check only when a define is declared

c++,class,operator-overloading,operators,element
I've create my own container that is inherited from a vector. I would like to reimplement operator[] in a way that makes checking for bounds decided by a #define. So putting an example, and ignoring template parmameters as they're complicated and irrelevant class MyArray : vector<double> { //... virtual double&...

Overloading Assignment operator in template based class

c++,templates,type-conversion,operator-overloading,template-meta-programming
I am writing a library to support a type of integers which have two template parameters INT_BITS and FRAC_BITS. I was successful in writing a convert function to convert different class types from one to another [ which vary in values of INT_BITS and FRAC_BITS ]. But when I try...

Overloading a binary operator for one operand in c++

c++,operator-overloading
Can you overload a binary operator to take only one operand in C++? I tried implementing this with a class similar to this: #include <iostream> using namespace std; class IntWrap { public: IntWrap operator=(int rhs) { val = rhs; return *this; } // No second operand for + IntWrap operator+()...

C++ compilation error, ambigous operator overloads

c++,class,operator-overloading,ambiguous
I have a template array class overloading both operator [] to access items and operator T * to get direct buffer access. template< typename T > class buffer { const T & operator [] ( size_t ) const; T & operator [] ( size_t ); operator const T * ()...

operator overload. q = q1+q2, q1 being modified but I want q1 and q2 to be intact

c++,visual-studio-2012,operator-overloading
I learnt operator overloading like 1 or 2 weeks ago and I think I know how it works but I'm trying to overload the operator + so it returns a new CCuaternion which is working well but CCuaternion(float w, float x, float y, float z) { this->w = w; this->x...

Templates with Operation for 2d array addition

c++,arrays,templates,operator-overloading
I have two 2d arrays arr1 this belongs to object s1 and arr2 this belongs to object s2 and I want to store the addition to the object s3. After a lot of searching and experimenting with this , this is my code: #include <iostream> #include <sstream> using namespace std;...

C++ method forwarding

c++,templates,c++11,operator-overloading,perfect-forwarding
I need to implement a class Container which acts exactly as the contained template class: template <typename T> class Container { public: //... private: // T data_; }; T can be either a predefined type (e.g., int) or a user-defined type. The purpose is to intercept any read/write operations done...

how to implement movable overloads without violating the DRY principle in C++?

c++,c++11,operator-overloading,rvalue-reference
While implementing method and operator overloading in some of my classes to leverage the rvalue references in C++, often I write some code with poor design violating the DRY Principle. What would be a better alternative for the code snippet below? (This code is just to illustrate the problem) class...

virtual operator overloading c++

c++,oop,inheritance,operator-overloading
Suppose I wanted to overload the "==" operator for a derived class, do I need to rewrite the overload in the derived class header file or is there a way to implement the operator overload in the .cpp file without having to add anything in the header file? And if...

Overloading multiplication operator fails

c++,operator-overloading
I am trying to write a RGB Class for a AVR project. But when i try to use it, it fails at some operators. Error 415 no match for 'operator*' (operand types are 'const float' and 'RGB') ...\Animation\Wall\Wall.cpp 321 18 Cube Here is how it looks: class RGB { //variables...

Temporary variable destroyed with overloaded + and += operator

c++,memory-management,operator-overloading
I am getting a segfault because I believe my temporary variable is being destroyed (freeing allocated memory) before the operators are done using it. This is the code in my main: int main(int argc, char *argv[]) { Bcd b1 = Bcd(100), b2 = Bcd(20), b3 = Bcd(50); b3 += b1...

equality operator overloading in swift enums with associated values

swift,enums,operator-overloading,equality
I know an almost similar question was asked earlier, but I am not able to comment on it, because I am to new here. That is the reason why I am posting a separat question. Also my question is an extension to the previous question asked and is aimed at...

overload std::string less than operator in c++

c++,string,stl,operator-overloading
I want to use map<string, int> to store strings with their occurance. due to the requirement, I have to overload the "<" operator for std::string, in a different order from the granted lexicographic order. I use a free function, as follows. bool operator<(const string& a, const string& b) { int...

How not to get lost in implementation of '<' for multi-variable structures

c++,operator-overloading,structure
Similarly to Preferred implementation of '<' for multi-variable structures I'm implementing a less-than operator for a structure with multiple values. I'm not worrying about using equality or less than operators, lets assume all the members correctly implement both. My structure has four fields and the operator is already getting quite...

Error C4716: 'operator<<': must return a value [closed]

c++,operator-overloading,systemc
I am struggling to get an appropriate return for this operator (it is not my code, just trying to correct it and I am not as good as I should be in C++ to correct it) can anybody help me with this, it is datatype class defined for high level...

OpenCV Mat (comparison) operators documentation

opencv,operator-overloading
Do you know where one could find documentation for cv::Mat operators, like <, <= etc? My current doubt is to know if the < operator returns ones or ~0 values (=255 for a uint8_t image, =65535 for a uint16_t image and so on). Reading here, it is implied that the...

C++ Ambigous call to constructor

c++,constructor,operator-overloading,implicit-conversion,explicit
I have a class with several constructors and overloaded operators : class Utf8String { public: Utf8String(); explicit Utf8String( const char * sStr ); Utf8String( const char * sStrBeg, const char * sStrEnd ); Utf8String( const char * sStr, uint32_t nCpCount ); explicit Utf8String( const Utf8String & sStr ); explicit Utf8String(...

I want to check if a class instance is already stored in a std::vector

c++,vector,operator-overloading
I hope the title describes my problem completely. Running the code I get an error: error C2678: binary '==':no operator found which takes a left-hand operand of tpye 'A' (or there is no acceptable conversion)" Where is the mistake and how can I fix the problem??? class A { private:...

Why I cannot put this operator overload in the same namespace as the struct?

c++,operator-overloading,ostream
I have the following code: #include <iostream> #include <vector> namespace X { std::ostream& operator<<(std::ostream& os,const std::vector<double>& v){ for (int i=0;i<v.size();i++){os << v[i] << " ";} return os; } namespace Y { struct A {std::vector<double> x;}; std::ostream& operator<<(std::ostream& os,const A& a){ os << a.x << std::endl; return os; } } }...

Fortran named operator

generics,fortran,operator-overloading,intel-fortran,named
I wrote a derived type and defined a named operator for it like this: module ModuleNamedOperator implicit none type TCoords contains procedure :: TCoordsFM generic,public :: operator(.fm.) => TCoordsFM end type contains type(TCoords) function TCoordsFM(self,IVal) result(this) class(TCoords),intent(in) :: self integer(4),intent(in) :: IVal this=self write(*,'(I0)') "IVal:",IVal end function TCoordsFM end module...

Is it possible to overload logical operators (&& e.g.) in Haskell?

haskell,operator-overloading
I'm working with many-valued logic and trying to overload basic logic functions. I haven't problem with overloading Num and Eq operators, but I don't know how to overload &&, || and not. Is it possible? Thanks for answers!...

Combining member access operators with overloaded call operator

c++,pointers,operator-overloading
Given a class Foo with overloaded Boo* operator()(unsigned int), how should the overloaded operator be accessed? I originally tried std::unique_ptr<Foo> foo_ptr(new Foo); Boo* boo_ptr = foo_ptr(1); But this doesn't work, so I tried: std::unique_ptr<Foo> foo_ptr(new Foo); Boo* boo_ptr = foo_ptr->(1); but this doesn't work either (and I didn't really expect...

C++ template for function call operator

c++,templates,operator-overloading
I tried to use template for function call operator overload as in the following program: #include <stdio.h> struct Apple { template <typename tn> tn value (); template <typename tn> tn operator () (); }; template <> int Apple::value () { return 10; } template <> int Apple::operator () () {...

C++ operator []

c++,c++11,operator-overloading
I am trying to implement the operator [] that is to be used once for Set and once as Get, i need to differentiate between the two cases, as in the case of get, i need to throw an exception if the returned value is equal to -1; whereas in...

C++: overloading the I/O operators

c++,io,operator-overloading
I am new to C++ and I can't seem to figure out overloading the I/O operators. I have read: Overloading operator<<: cannot bind lvalue to ‘std::basic_ostream<char>&&’ Overloading operator<<: cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’ std::ostream {aka std::basic_ostream<char>} Ivalue to 'std::basic_ostream<char>&& Overloading the I/O operators on Learn cpp but I, unfortunately,...

What is the difference between overloading the assignment operator and any other operator?

c++,oop,operator-overloading,assignment-operator
I want to know if there is any difference between simple binary operator overloading and assignment operator overloading.

How does Dart's operator overloading translate to javascript?

javascript,dart,operator-overloading,operators,overloading
Very happy to see Dart support operator overloading (very cool :) ), but I am curious as to how this implementation translates to Javascript before I dive into developing something around this? Know this isn't something Javascript supports natively so wondered if there would be any complications around conversion to...

Understanding copy constructor in C++ [duplicate]

c++,operator-overloading,copy-constructor
This question already has an answer here: What are copy elision and return value optimization? 4 answers I am trying to understand the concept of copy constructors in C++. I have written the following program: #include<iostream> using namespace std; class Box{ private: int d; public: Box(int i){ cout <<...

String Concatenation Operator + Ambiguity

string,operator-overloading,operators,concatenation,language-design
I am currently working on a JVM-based programming language that supports operator overloading and custom operators. I wanted to stick to Java and use the + operator for String concatenation, and this is implemented and works flawlessly in my language. However, the operator is also used in various other places,...

Overloading conversion operator in c++

c++,operator-overloading
when a operator function is implemented as a member function left most operand must be object of operator's class but in code below #include<iostream> using namespace std; class ffloat { private: float a; public: ffloat():a(34.566){} operator int () { return a=static_cast<int >(a); } }; int main() { ffloat w; int...

C++: Associativity of * (multiply) operator is not left-to-right

c++,operator-overloading,operator-keyword,associativity
While working on a school assignment, we had to do something with operator overloading and templates. All cool. I wrote: template<class T> class Multiplication : public Expression<T> { private: typename std::shared_ptr<Expression<T> > l, r; public: Multiplication(typename std::shared_ptr<Expression<T> > l, typename std::shared_ptr<Expression<T> > r) : l(l), r(r) {}; virtual ~Multiplication() {};...

ostream must take exactly one argument

c++,operator-overloading
I am getting a compile error in my output stream operator and I cannot seem to find out how to fix it as I never received this error before: linkedList.cpp:258: error: ‘std::ostream& linkedList<T>::operator<<(std::ostream&, linkedList<T>)’ must take exactly one argument make: *** [linkedList.o] Error 1 Here is the definition of my...

operator overloading in abstract class(interface)

c++,interface,operator-overloading,abstract-class
I want to have an abstract class IMatrix which contains pure virtual members and one of them is an operator overloading member. template <typename T> class IMatrix { public: virtual T operator+(const T& b)=0; }; and for the implementation I want to use a third party matrix class as for...

Contradictory Error Messages - Operator Overloading <<

c++,operator-overloading,syntax-error,friend
Problem Depending on how I write a function in my class, I get one of 2 contadictory error messages when trying to overload the << operator as a friend of my class. The error messages are as follows: // With two arguments (engine.cpp) error: 'std::ostream& game::GameEngine::operator<<( std::ostream&, const Engine& )'...

What is the right way to overload the plus operator?

c++,c++11,operator-overloading
I have set of classes: class A { public: A(B b) {//..} A(C C) {//..} A(D D) {//..} A& operator+=(A const& ls) {//..} A operator+(A const& ls) const {//..} } class B { //.... } class C { //.... } class D { //.... } I want to support the...

C++ Operator Overload << Errors. SafeMatrix 2D Array

c++,arrays,templates,pointers,operator-overloading
I am having issues with running this code. It's supposed to be a templated 2D array with constructors, destructors, copy constructors, and operator overloads. My main issue is in the ostream& operator<<(ostream& os, SafeMatrix<class T> s) overloader that's causing the errors. In main, when I cout<<b[0][0], it prints fine, but...

StarUML - Operator Overloading

c++,operator-overloading,staruml
How do I show an overloaded operator in starUML. I have overloaded the assignment, equality and array operators. (If that matters) Thanks...

Template class implementing comparison operators

c++,templates,operator-overloading
It is a frequent task of mine to write all the overloaded comparison operators to a class, so I've written a template class which implements <,<=,>=,!= if the derived class implements == and <. It is working but features a lot of cast and the not that obvious "Curiously recurring...

Overloading the extraction operator

c++,file,operator-overloading
I'm overloading the extraction operator to read a node which contains a pair of numbers. As you can see I'm printing a message for the user to know which number they are writing. However when I read from a file the messages will still print. So I want to know...

Overloading fstream << operator to save “any” kind of data

c++,save,operator-overloading,ostream
I have created a Test class that has a public variable double x. I have overloaded the ostream << operater to be able to print out the variable x. I have also written an external save(filename, object) function that would save the content of the object in a particular way....

C++ operator overloading >= with 2 different returns

c++,return,operator-overloading
I've got a class which looks like this: class Player { friend bool operator>=(Player &pl1, Player &pl2) { return true; }; private: int nr, height, weight; } A player has a number, height and weight. Now I'd like to know if Player1 is bigger and/or heavier than Player2. After this...

Operator overloading code compilation error, template argument deduction/substitution failure

c++,gcc,operator-overloading,argument-passing
I'm trying to apply some concepts of operator loading that I've learnt in the following C++ class. #include<iostream> using namespace std; class Point { private: int x, y; public: Point(int, int); Point operator+(const Point&); friend istream& operator>>(istream& in, Point&); friend ostream& operator<<(ostream& out, Point&); Point operator=(const Point&); }; Point::Point(int x...

Overloading +/- operators to add/subtract vectors

c++,operator-overloading
I am working on a class for a c++ project, and I have to overload all of my operators to work on vectors. Specifically, I define my vector as follows: template<class Type> ThreeVector<Type>::ThreeVector(Type x, Type y, Type z) { mx=x; my=y; mz=z; } And my +operator as: template<class Type> ThreeVector<Type>...

Avoiding to defer “child” object construction with `operator<<`

c++,constructor,operator-overloading,variadic-templates,c++14
Let's say I have a container object that stores an std::vector of polymorphic children. struct Child { Child(Parent& mParent) { /* ... */ } virtual ~Child() { } }; class Parent { private: std::vector<std::unique_ptr<Child>> children; template<typename T, typename... TArgs> auto& mkChild(TArgs&&... mArgs) { // `static_assert` that `T` is derived from...

C++ Overloading operator= to get right and left hand overload

c++,operator-overloading
This is more of an, I always wanted to know scenario. In the following code, tclass has one int as a private member. You can see the operator= overload. If you look at the main code, you see the bbb which is a tclass object. in one line bbb =...

implicit assignment operators [C++]

c++,operator-overloading,assignment-operator
if i have an operator overload on my class, is the assignment version of the operator implicitly created as well? class square{ square operator+(const square& B); void operator=(const square& B); }; As in, can I then call square A, B; A += B; with the compiler implicitly deciding to call...

How to invoke short-circuit logical operators in MATLAB as a function?

matlab,operator-overloading,logical-operators,low-level,short-circuiting
MATLAB operators usually translate into a function form as in the following examples: ~A => not(A) A + B => plus(A,B) A(...) => subsref(...) A(...) = ... => subsasgn(...) etc. Now please consider the operators && and ||. The various documentation (1-doc for or, 2-doc for and, 3-the MATLAB Programming...

c++ operator overloading and associated namespace

c++,namespaces,operator-overloading,clang,argument-dependent-lookup
The following simplified example compiles in gcc and Visual Studio, but fails in clang !? namespace N { struct A {}; template <typename T> double operator+ (T a, double d) {return d;} template <typename T> double operator+ (double d, T a) {return d;} } void test() { N::A a; double...

What does the round brackets“()”-overloading mean in this example

c++,multithreading,operator-overloading
I'm a rookie in C++. I learn a simple example (see the code below). I can not undersand what is the purpose of the overloading "()". Is the "overloading ()" used in std::thread my_thread(my_func);? Thank for all your attention. struct func { int& i; func(int& i_) : i(i_) {} **void...

Handle a value being changed in a c++ struct

c++,struct,operator-overloading,detection
I have a struct that describes how the system should be initialised. I then have a method that returns a reference to said struct so that the user of the final system can change certain options after initialisation. I wish to detect when a value is changed and tell the...

C++ operator overloading for wrapper class

c++,pointers,operator-overloading,wrapper
I'm using a class called Pointer, which is some kind of a wrapper around a real pointer I guess. I think this line of code in this class enables me to get the real pointer: operator const T* () const; What does this mean exactly? How can I call this?...

Polymorphic operator<< from virtual base class

c++,inheritance,polymorphism,operator-overloading
I want to overload Operator<< to do a specialized operation within a context of polymorphic classes. To give a direct example of what I want (using int as an example): Base* a = new A; (*a) << 10; I would like to use this syntax because another portion of my...

Passing a reference to template function call operator overload

c++,visual-studio-2013,operator-overloading,windows-8.1,function-call-operator
I have a class which overloads the function call operator with a template function, like so: class Test { public: template<class T> void operator()(T t) { std::cout<<(&t)<<std::endl; }; }; I'd like to call it with a reference argument, however when trying to do so, it passes the argument as a...

Operator Overloading without memory copies

c++,memory-management,operator-overloading
Imagine we have the type A and we want to do the following operation: A operator -(const A& a, const A& b) { A c; //... return c; } When we call this operator, we do something like this: A c; c = a - b; Basically we are allocating...

Overload operator for int and char in c++

c++,char,operator-overloading
I want to have a class that can accept assignment from both and int and a string literal. The string literal, it turns out, must be of type char[]. I actually have a whole lot of data types that are all successfully taken by the assignment operator. But the compiler...

Detect self-assignment in overloaded C++ operators

c++,class,operator-overloading
Forgive me if this is a duplicate; I searched but the correct vernacular may be outside my scope of comprehension. My goal for some arbitrary class and overloaded operator x = x op y would recognize it is being self-assigned and rather than generating a temporary variable just op= to...

c++ emulate typecasting using assignment operator

c++,c++11,constructor,operator-overloading
This is my class -- class stuff { private: char s_val = 'x'; char e_val = 'y'; public: stuff() {;} stuff(const string &s) { this->s_val = s[0]; this->e_val = s[s.length() - 1]; } stuff(const stuff &other) { this->s_val = other.s_val ; this->e_val = other.e_val ; } stuff& operator=(const stuff &other)...

operator[] overload in bit-field manipulation?

c++,operator-overloading,bit-fields
I am working on an arduino-like platform (very limited RAM), and I need to use a bit-field. I need to modify a specific bit in a byte, with something like this: OneByte myByte = 0b11101111; myByte[5] = 1; To achieve this, I wrote the following: typedef struct { uint8_t bit0:1;...

Understanding an overloaded operator[] example

c++,operator-overloading,operators,overloading,binary-operators
I am confused with a question that I saw in a c++ test. The code is here: #include <iostream> using namespace std; class Int { public: int v; Int(int a) { v = a; } Int &operator[](int x) { v+=x; return *this; } }; ostream &operator<< (ostream &o, Int...

how to overload an assignment operator in swift

ios,swift,operator-overloading
I would like to override the '=' operator for a CGFloat like the follow try : func = (inout left: CGFloat, right: Float) { left=CGFloat(right) } So I could do the following: var A:CGFLoat=1 var B:Float=2 A=B Can this be done ? I get the error Explicitly discard the result...

Cast integral array to class array

c++,operator-overloading
I'm using a library passes me a pointer to an array of int32_T. I need to do some math on these numbers, but the data is actually in Q23.8 format. I created a class overloading the basic math operators, but I'm stuck with how to cast the int32_t array pointer...

bi-directional operator overloading

c++,operator-overloading
Code Vector.h friend Vector& operator* (const double &factor, const Vector &v); friend Vector& operator* (const Vector &v,const double &factor); Vector.cpp Vector& operator *(const double &factor, Vector &v){ v.x=v.x*factor; v.y=v.y*factor; return v; } Vector& operator* (const Vector &v,const double &factor){ return factor * v; } And for some readon i get...

C++: operator overloading: in-class and out-class. Ambiguity with preincrement operator

c++,operator-overloading,pre-increment
Check it out this code: struct A { A operator+(A const& a) { cout << 1 << endl; return A(); } A& operator++() { cout << 2 << endl; return *this; } A operator++(int) { cout << 3 << endl; return *this; } bool operator!() { cout << 4 <<...

C++ code improvement, array out of bounds

c++,arrays,class,operator-overloading
This is a class template for an Array. I overloaded the [ ] operator in hopes it would fix the "out of bounds" issue. The print outs work well, except if it falls out of range, the compiler enables the range by default and it displays a 6 digit number....

C++ Reading from txt file into object binary tree

c++,operator-overloading,iostream
***Edited code with my changes--not getting access violation anymore and it's assigning all my values perfectly except for the Customer ID--it's just leaving that blank. Is that because the ID is numeric and not technically a string?? This is homework--We are supposed to read data from a .txt file, then...

How to return dynamic object from operator function?

c++,operator-overloading,dynamic-memory-allocation,return-type
I am quite confused about this. How to return a dynamically allocated object from operator function? Consider following example: #include "stdafx.h" #include <iostream> #include "vld.h" using std::cout; class Point { public: Point(int x,int y) : a(x),b(y) { } Point() { } Point operator + (Point p) { Point* temp=new Point();...

c++ map array operator overloading enable setting value to

c++,operator-overloading,stdmap
i try to do ordered map ( simple very simple ) i want to overload the map "[] = value " operator . that is the equal sign that come after the array operator but how ? i have this : template <typename K, class V> class OrderedMap { public:...

Overload Single Equals in swift

ios,swift,operator-overloading
I have a strange situation where I can't seem to get single equals to overload This works fine: public func /=<T: ConvertibleUnit>(inout left: T, right: Int) { left.value = (left.value / Double(right)) } As soon as i change it to: public func =<T: ConvertibleUnit>(inout left: T, right: Int) { left.value...