C++ 条件运算符 ? :求公共类型

时间:2022-09-08 11:12:51

这段时间看C++标准库,看到有一个求公共类型的实用函数common_type<>;其实现是如下:

template<typename T1,typename T2>
struct common_type<T1,T2>
{
    typedef decltype(true?declval<T1>(),declval<T2>()) type;
}
刚开始还觉得奇怪,条件永远为true,不就是直接计算T1吗,想当然的以为产生公共类型不就是T1的类型吗?后然通过一个实例上机实验才发现不是这么回事。于是找到关于条件运算符的说明;我们知道条件运算符?:是C++中唯一的一个三目运算符。用法

expression ? expression : expression

下面是msdn对条件运算符的解释。from: http://msdn.microsoft.com/en-us/library/e4213hs1(v=vs.110).aspx

The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows:

  • The first operand is implicitly converted to bool. It is evaluated and all side effects are completed before continuing.

    第一个操作数自动转换成bool类型值。

  • If the first operand evaluates to true (1), the second operand is evaluated.

  • If the first operand evaluates to false (0), the third operand is evaluated.

The result of the conditional operator is the result of whichever operand is evaluated — the second or the third. Only one of the last two operands is evaluated in a conditional expression.

Conditional expressions have right-to-left associativity(从右至左结合性). The first operand must be of integral or pointer type. The following rules apply to the second and third expressions:

  • If both expressions are of the same type, the result is of that type. 

  • If both expressions are of arithmetic or enumeration types, the usual arithmetic conversions (covered in Arithmetic Conversions) are performed to convert them to a common type.  //如果两个表达式类型不相同,但是都是算术或者是枚举类型。那么算术转换将他们转换成共同类型。

  • If both expressions are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer conversions are performed to convert them to a common type. //指针类型转换

  • If both expressions are of reference types, reference conversions are performed to convert them to a common type. //引用类型转换

  • If both expressions are of type void, the common type is type void. //void 最低级的类型 

  • If both expressions are of a given class type, the common type is that class type. //类类型的基本转换是他的基类的类型。

Any combinations of second and third operands not in the preceding list are illegal. The type of the result is the common type, and it is an l-value if both the second and third operands are of the same type and both are l-values.

通过上面的说明可以看到common_type是通过隐式类型转换来实现的。看来对一些基本概念的掌握还是不牢固啊。