I'm trying to learn more about how operator overloading works.
I understand that overloading the comma operator may not be the best idea, but this is for instructional purposes only.
I'm expecting the following code to use my overloaded operator (I used brackets as I'm aware the comma operator has the lowest precedence) to construct a vector containing (1,2) and then call the vector's assignment operator.
However, I get an error:
no known conversion from argument 1 from 'int' to 'const std::vector<int>&'
I don't understand why this is happening. (1,2) should construct a vector so it shouldn't be trying to convert from an int
to a 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;
}
The purpose of comma operator is to string together several expressions. The value of a comma-separated list of expressions is the value of the right-most expression.
The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.
1) Comma as an operator: The comma operator (represented by the token, ) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator, and acts as a sequence point.
There is already a built-in definition for the comma operator applied to ints. Your template isn't even in the running for overload resolution, since you can't overload operators unless at least one of the arguments is a user defined type.
You could 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 take a look at Boost.Assign, which allows constructions like this:
std::vector<int> a;
a += 1,2,3,4,5,6,7,8;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With