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.
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.
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