Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to Overload the Comma Operator?

I see questions on SO every so often about overloading the comma operator in C++ (mainly unrelated to the overloading itself, but things like the notion of sequence points), and it makes me wonder:

When should you overload the comma? What are some examples of its practical uses?

I just can't think of any examples off the top of my head where I've seen or needed to something like

foo, bar; 

in real-world code, so I'm curious as to when (if ever) this is actually used.

like image 794
user541686 Avatar asked Apr 09 '11 00:04

user541686


People also ask

When should an operator be overloaded?

Now, if the user wants to make the operator “+” to add two class objects, the user has to redefine the meaning of the “+” operator such that it adds two class objects. This is done by using the concept “Operator overloading”.

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. Essentially, the comma's effect is to cause a sequence of operations to be performed. The values of the other expressions will be discarded.

What are the rules for overloading the operators?

1) Only built-in operators can be overloaded. New operators can not be created. 2) Arity of the operators cannot be changed. 3) Precedence and associativity of the operators cannot be changed.

What is the purpose of the comma operator?

The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.


2 Answers

I have used the comma operator in order to index maps with multiple indices.

enum Place {new_york, washington, ...};  pair<Place, Place> operator , (Place p1, Place p2) {     return make_pair(p1, p2); }   map< pair<Place, Place>, double> distance;  distance[new_york, washington] = 100; 
like image 108
Petter Avatar answered Oct 04 '22 15:10

Petter


Let's change the emphasis a bit to:

When should you overload the comma?

The answer: Never.

The exception: If you're doing template metaprogramming, operator, has a special place at the very bottom of the operator precedence list, which can come in handy for constructing SFINAE-guards, etc.

The only two practical uses I've seen of overloading operator, are both in Boost:

  • Boost.Assign
  • Boost.Phoenix – it's fundamental here in that it allows Phoenix lambdas to support multiple statements
like image 32
ildjarn Avatar answered Oct 04 '22 15:10

ildjarn