smallB
smallB

Reputation: 17118

Questionable definition of common_type

in book "The Cpp standard library", 2nd edition, by Nicolai M. Josuttis, says (5.4, p.125) that definition of struct common type is following:

template <typename T1, typename T2>
struct common_type<T1,T2> {
typedef decltype(true ? declval<T1>() : declval<T2>()) type;
};

I have serious problems to believe that this is correct definition of common_type. Reason:

typedef decltype(true ? declval<T1>() : declval<T2>()) type;//As far as I understand this will always pick second operand, declval<T1>(), due to the fact that there is 'true' value. Am I right?

Upvotes: 3

Views: 187

Answers (1)

Eugene Mamin
Eugene Mamin

Reputation: 749

It's all about conditional operator. It isn't selection statement like if or switch.

5.16 paragraph of ISO C++11 standard:

Otherwise, if the second and third operand have different types and either has (possibly cv-qualified) class type, or if both are glvalues of the same value category and the same type except for cv-qualification, an attempt is made to convert each of those operands to the type of the other.

So, it doesn't matter that decltype contains true condition, compiler have to choose common type as result.

UPD: 5.16 contains further description of correct behavior, you should see it for completely understanding entire process. But for your particular question:

Using this process, it is determined whether the second operand can be converted to match the third operand, and whether the third operand can be converted to match the second operand. If both can be converted, or one can be converted but the conversion is ambiguous, the program is ill-formed. If neither can be converted, the operands are left unchanged and further checking is performed as described below. If exactly one conversion is possible, that conversion is applied to the chosen operand and the converted operand is used in place of the original operand for the remainder of this section.

Upvotes: 4

Related Questions