Operator comma overload

I am trying to learn more about how operator overloading works.

I understand that operator overloading with a comma may not be the best idea, but this is for educational purposes only.

I expect the following code to use my overloaded operator (I used parentheses because I know that the comma operator has the lowest priority) to build a vector containing (1,2), and then call the vector assignment operator.

However, I get the error message:

no known conversion from argument 1 from 'int' to 'const std::vector<int>&' 

I do not understand why this is happening. (1,2) should build a vector, so shouldn't it try to convert from int to vector<int> ?

 #include <vector> #include <utility> using std::vector; using std::move; template <typename T> vector<T> operator,(const T& v1, const T& v2) { vector<T> v; v.push_back(v1); v.push_back(v2); return move(v); } int main() { vector<int> a; a = (1,2); return 0; } 
+5
source share
2 answers

There is already a built-in definition for the comma operator applied to ints. Your template does not even work to allow overloading, since you cannot overload statements if at least one of the arguments is not a user-defined type.

You can do something like this:

 template<typename T> struct vector_maker { std::vector<T> vec; vector_maker& operator,(T const& rhs) { vec.push_back(rhs); return *this; } std::vector<T> finalize() { return std::move(vec); } }; int main() { auto a = (vector_maker<int>(),1,2,3,4,5).finalize(); } 

Or look at Boost.Assign , which allows you to create such constructs:

 std::vector<int> a; a += 1,2,3,4,5,6,7,8; 
+19
source

The expression on the right side of the assignment is evaluated simply as (1,2) and degenerates to (2) or 2 , which is int .

Then the calculation is performed. The left side is of type vector<int> . You are trying to assign 2 (an int ) to a (a vector<int> ), and since there is no conversion from int to vector<> , you get an error.

You cannot overload operators for built-in types, such as int .

+2
source

All Articles