Below is one of the specializations of std::common_type.
template <class T, class U>
struct common_type<T, U> {
typedef decltype(true ? declval<T>() : declval<U>()) type;
};
My notion is that the conditional statement is unnecessary. If it’s checking against true, won’t the expression invariably resolve to declval<T>()? And if so, how does the returned typedef justify the definition…
“Determines the common type among all types
T..., that is the type allT...can be implicitly converted to.”
Can someone please explain the conditional statement? Is it accurate that the check against true is superfluous, and that the condition will always resolve to the first operand? And if so, how does the type that is returned satisfy the definition?
The ternary operator’s type isn’t just the type of the branch the compiler knows it has to take. It is the type which is common to both branches if there is such a type. If there is no such type, the compilation fails. The ternary operator is the only operator with the property that it converts to the common type of the expressions rather than to the result of an expression on two values. That is, the ternary operator is just abused to obtain the common type. The condition is immaterial, however.
The relevant section in the standard is 5.16 [expr.cond] paragraph 3:
Following the paragraph are the rules of how the common type is provided. The otherwise refers to the case that either the second or the third expression is throw-expression or one or both of the second or the third expression have type
void.