common type

Hi, I just found out how the common_type traits is being implemented and I don't really understand one part of it. This is the magic line that picks the common type from 2 types

For example
 
decltype(true ? std::declval<int>() : std::declval<double>())

gives the result double

If the 1st part of expression is always true? how can this actually be working. I tested it out and the true can also be changed to false and it would still work.

This post just basically tells that it works - deal with it :D
http://stackoverflow.com/questions/12290046/stdcommon-type-implementation

I always thought that it works like this
(condition) ? (if_true) : (if_false)
is basically the same as:
1
2
3
4
if (condition)
    if_true;
else
    if_false;

but in this case compiler doesn't care about condition at all and it just somehow picks the common type of 2 types. How is this exactly even working?
decltype doesn't evaluate the expression so it doesn't matter what values are being used. What matters are the types.

In C++ the return type of an expression is always known at compile time. It is not possible for the expression to sometimes return one type and in other situation return some other type. This is true also for the ternary operator. The type that the ternary operator returns is the common type of two types.
Last edited on
Ohh I think I finally understand now :) Tnx a lot man!!
Topic archived. No new replies allowed.