由std::common_type知道的?:运算符的不为人知的规则

std::common_type的原理大概是true? A : B, 而true是个常量,为啥A : B的类型是common type呢?

这里参见:https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/e4213hs1(v=vs.110)?redirectedfrom=MSDN

Remarks

The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows:

  • The first operand is implicitly converted to bool. It is evaluated and all side effects are completed before continuing.

  • If the first operand evaluates to true (1), the second operand is evaluated.

  • If the first operand evaluates to false (0), the third operand is evaluated.

The result of the conditional operator is the result of whichever operand is evaluated — the second or the third. Only one of the last two operands is evaluated in a conditional expression.

Conditional expressions have right-to-left associativity. The first operand must be of integral or pointer type. The following rules apply to the second and third expressions:

  • If both expressions are of the same type, the result is of that type.

  • If both expressions are of arithmetic or enumeration types, the usual arithmetic conversions (covered in Arithmetic Conversions) are performed to convert them to a common type.

  • If both expressions are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer conversions are performed to convert them to a common type.

  • If both expressions are of reference types, reference conversions are performed to convert them to a common type.

  • If both expressions are of type void, the common type is type void.

  • If both expressions are of a given class type, the common type is that class type.

Any combinations of second and third operands not in the preceding list are illegal. The type of the result is the common type, and it is an l-value if both the second and third operands are of the same type and both are l-values.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值