三元运算符
是否有任何逻辑原因可以解释为什么在三元选项中两个分支必须具有相同的基本类型或可以转换为一种?没有这个规则有什么问题呢?为什么我不能做这样的事情(这不是最好的例子,但澄清了我的意思):
int var = 0;
void left();
int right();
var ? left() : right();
Is there any logical reason that will explain why in ternary optor both branches must have the same base type or be convertible to one? What is the problem in not having this rule? Why on earth I can't do thing like this (it is not the best example, but clarifies what I mean):
int var = 0;
void left();
int right();
var ? left() : right();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
表达式必须具有编译时已知的类型。您不能使用“X 或 Y”类型的表达式,它必须是其中之一。
考虑这种情况:
将调用哪个重载?这是一个简单的情况,还有一些更复杂的情况,例如模板,必须在编译时知道。因此,在上述情况下,编译器不会根据条件选择重载,它必须选择一个重载来始终调用。
它不能这样做,因此三元运算符的结果必须始终是相同的类型(或兼容)。
Expressions must have a type known at compile time. You can't have expressions of type "either X or Y", it has to be one or the other.
Consider this case:
Which overload is going to be called? This is a simple case, and there are more complicated ones involving e.g. templates, which have to be known at compile time. So in the above case, the compiler won't choose an overload based on the condition, it has to pick one overload to always call.
It can't do that, so the result of a ternary operator always has to be the same type (or compatible).
三元运算符返回它所采用的分支的值。如果两个分支不具有相同的类型,则表达式将具有不确定的类型。
The ternary operator returns the value of the branch it takes. If the two branches didn't both have the same type, the expression would have an indeterminate type.
要点是表达式应该具有静态定义的类型。
如果三元运算符的分支不兼容,则无法静态推导三元表达式类型。
The point is that an expression should have a statically defined type.
If branches of your ternary operator are incompatible, you cannot statically deduce the ternary expression type.
我猜是因为三元运算符必须有一个定义的返回值。如果两个分支的类型不同或无效,则很难做到。
I guess because the ternary operator must have a defined return value. Hard to do if the types of both branches is different, or void.