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 desi
One of the principles of the ternary operator is that the true / false expression are only evaluated based on the truth or falseness of the conditional expression.
cond ? expr1 : expr2
In this example expr1 is only evaluated if cond is true while expr2 is only evaluated if cond is false. Keeping that in mind lets look at what a signature for ternary overloading would look like (using fixed types here instead of a template for simplicity)
Result operator?(const Result& left, const Result& right) {
...
}
This signature simply isn't legal because it violates the exact semantics I described. In order to call this method the language would have to evaluate both expr1 and expr2 hence they are no longer conditionally evaluated. In order to support ternary the operator would either need to
expr1 or expr2EDIT
Some may argue that the lack of short circuiting in this scenario is fine. The reason being that C++ already allows you to violate short circuiting in operator overloads with || and &&
Result operator&&(const Result& left, const Result& right) {
...
}
Though I still find this behavior baffling even for C++.