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.