Why is it not possible to overload the ternary operator?

前端 未结 5 1711
时光说笑
时光说笑 2020-12-05 14:39

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

5条回答
  •  渐次进展
    2020-12-05 15:15

    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

    1. Take a lambda for each value so it could produce them on demand. This would necessarily complicate the calling code though because it would have to take into account lambda call semantics where no lambda was logically present
    2. The ternary operator would need to return a value to denote whether the compiler should use expr1 or expr2

    EDIT

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

提交回复
热议问题