Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator comma overloading

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;
}
like image 265
Jack Avatar asked Apr 27 '16 21:04

Jack


People also ask

What is comma operator overloading in C++?

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.

What is comma operator explain with example?

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.

What operator is comma?

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.


1 Answers

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;
like image 119
Benjamin Lindley Avatar answered Oct 22 '22 10:10

Benjamin Lindley