Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not possible to overload the ternary operator?

Tags:

Why is it not possible to overload the ternary operator ' ?: '?

I use the ternary operator often to consolidate if statements, and am curious why the language designers chose to forbid this operator from being overloaded. I looked for an explanation as to why in C++ Operator Overloading but did not find one describing why this isn't possible. The only information the footnote provides is that it cannot be overloaded.

My initial guess is that overloading the operator will almost always violate number one or two of the principles given in the link above. The meaning of the overload will rarely be obvious or clear or it will deviate from its original known semantics.

So my question is more of why is this not possible rather than how, as I know it cannot be done.

like image 334
Paul Renton Avatar asked Jul 30 '13 17:07

Paul Renton


1 Answers

if you could override the ternary operator, you would have to write something like this:

xxx operator ?: ( bool condition, xxx trueVal, xxx falseVal ); 

To call your override, the compiler would have to calculate the value of both trueVal and falseVal. That's not how the built-in ternary operator works - it only calculates one of those values, which is why you can write things like:

return p == NULL ? 23 : p->value; 

without worrying about indirecting through a NULL pointer.

like image 135
Marshall Clow Avatar answered Oct 13 '22 00:10

Marshall Clow