Operator Precedence in Conditional Operator

Viewed 82

So I was experimenting with some templates recently, and this was the code that I stumbled upon:

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

So it's basically a bunch of conditional operators that return a value if true, or none at all if false. And if you add them up together, you can determine what data type the argument is.

However, I realized something. Do brackets matter? I tried putting brackets around the code like so:

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

But the output is still the same. So I was thinking maybe the compiler sees something like this:

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

So in a way, it kind of evaluates the last conditional operator first, and works it's way backwards. But I still can't wrap my head around this thing, and I'm not sure if I'm understanding this correctly.

Could anyone tell me what's the operator precedence here, and how it's getting executed? Thanks.

1 Answers

Yes, operator+ has higher precedence than condition operator, so

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;

is interpreted as

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;

and be more clear

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

It'll give the result as 1 for bool, 2 for char, 3 for int.

About 0 + std::is_same<T, ...>::value, std::is_same<T, ...>::value is a bool, when used as the operand of operator+, it'll be converted to int implicitly as 1 for true, 0 for false. After that the addition result is used as the condition and converted to bool back as false for 0 and true for non-zero.

Related