三元运算符

发布于 2024-10-12 05:34:36 字数 189 浏览 3 评论 0原文

是否有任何逻辑原因可以解释为什么在三元选项中两个分支必须具有相同的基本类型或可以转换为一种?没有这个规则有什么问题呢?为什么我不能做这样的事情(这不是最好的例子,但澄清了我的意思):

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

坚持沉默 2024-10-19 05:34:36

表达式必须具有编译时已知的类型。您不能使用“X 或 Y”类型的表达式,它必须是其中之一。

考虑这种情况:

void f(int x) {...}
void f(const char* str) {...}

f(condition ? 5 : "Hello");

将调用哪个重载?这是一个简单的情况,还有一些更复杂的情况,例如模板,必须在编译时知道。因此,在上述情况下,编译器不会根据条件选择重载,它必须选择一个重载来始终调用。

它不能这样做,因此三元运算符的结果必须始终是相同的类型(或兼容)。

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:

void f(int x) {...}
void f(const char* str) {...}

f(condition ? 5 : "Hello");

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

浅听莫相离 2024-10-19 05:34:36

三元运算符返回它所采用的分支的值。如果两个分支不具有相同的类型,则表达式将具有不确定的类型。

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.

故乡的云 2024-10-19 05:34:36

要点是表达式应该具有静态定义的类型。

如果三元运算符的分支不兼容,则无法静态推导三元表达式类型。

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.

醉城メ夜风 2024-10-19 05:34:36

我猜是因为三元运算符必须有一个定义的返回值。如果两个分支的类型不同或无效,则很难做到。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文