Why is it not possible to overload the ternary operator?

前端 未结 5 1699
时光说笑
时光说笑 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:13

    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.

提交回复
热议问题