首页 > 解决方案 > 条件运算符中的运算符优先级

问题描述

所以我最近在尝试一些模板,这是我偶然发现的代码:

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));
}

所以在某种程度上,它首先评估最后一个条件运算符,然后向后工作。但我仍然无法理解这件事,我不确定我是否理解正确。

谁能告诉我这里的运算符优先级是什么,以及它是如何执行的?谢谢。

标签: c++operator-precedenceconditional-operator

解决方案


是的,优先级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 ) );

它会给出1for bool, 2for char, 3for的结果int

About 0 + std::is_same<T, ...>::value,std::is_same<T, ...>::value是 a bool, 当用作 的操作数时operator+, 将int隐式转换为1for true, 0for false。之后,将加法结果用作条件并转换为非零bool值和非零值。false0true


推荐阅读