c++ - 条件运算符中的运算符优先级
问题描述
所以我最近在尝试一些模板,这是我偶然发现的代码:
template <typename T>
int someFunction(T someParameter)
{
return std::is_same<T, bool>::value ? 1 : 0 +
std::is_same<T, char>::value ? 2 : 0 +
std::is_same<T, int>::value ? 3 : 0;
}
所以它基本上是一堆条件运算符,如果为真则返回一个值,如果为假则根本不返回一个值。如果你把它们加在一起,你可以确定参数是什么数据类型。
然而,我意识到了一件事。括号重要吗?我试着像这样在代码周围加上括号:
template <typename T>
int someFunction(T someParameter)
{
return (std::is_same<T, bool>::value ? 1 : 0) +
(std::is_same<T, char>::value ? 2 : 0) +
(std::is_same<T, int>::value ? 3 : 0);
}
但输出仍然相同。所以我在想也许编译器会看到这样的东西:
template <typename T>
int someFunction(T someParameter)
{
return std::is_same<T, bool>::value ? 1 : (0 +
std::is_same<T, char>::value ? 2 : (0 +
std::is_same<T, int>::value ? 3 : 0));
}
所以在某种程度上,它首先评估最后一个条件运算符,然后向后工作。但我仍然无法理解这件事,我不确定我是否理解正确。
谁能告诉我这里的运算符优先级是什么,以及它是如何执行的?谢谢。
解决方案
是的,优先级operator+
高于条件运算符,所以
return std::is_same<T, bool>::value ? 1 : 0 +
std::is_same<T, char>::value ? 2 : 0 +
std::is_same<T, int>::value ? 3 : 0;
被解释为
return std::is_same<T, bool>::value ? 1 :
( 0 + std::is_same<T, char>::value ) ? 2 :
( 0 + std::is_same<T, int>::value ) ? 3 : 0;
并且更清楚
return std::is_same<T, bool>::value ? 1 :
( ( 0 + std::is_same<T, char>::value ) ? 2 :
( ( 0 + std::is_same<T, int>::value ) ? 3 : 0 ) );
它会给出1
for bool
, 2
for char
, 3
for的结果int
。
About 0 + std::is_same<T, ...>::value
,std::is_same<T, ...>::value
是 a bool
, 当用作 的操作数时operator+
, 将int
隐式转换为1
for true
, 0
for false
。之后,将加法结果用作条件并转换为非零bool
值和非零值。false
0
true
推荐阅读
- node.js - egg-sequelize server online error: Class constructor LRUCache cannot be invoked without 'new'?
- javascript - 未捕获(承诺):NullInjectorError: StaticInjectorError(AppModule)[CdkConnectedOverlay -> Overlay]
- jquery - 在全屏覆盖中定位的问题
- javascript - Mobx-state-tree 操作在 Visual Studio 代码中不可用
- c# - C# 在自定义表单设计器上实现剪切/复制/粘贴
- ios - 想要那个 .scroll 动画,即使数据源没有在 UIPageViewController 中设置
- sql - 如何使用两个 CONNECT BY LEVEL 提高查询效率?
- redis - 通过 StackExchange.Redis 在 Redis 中的二级索引
- swift - 我需要在其路径中使用编码的前言斜杠快速创建一个 URL(没有层次意义)
- c# - 关于广告的 Unity 主线程问题