Ral*_*zky 16 c++ templates types metaprogramming c++11
模板类std::common_type计算可变参数类型列表的公共类型.它是x:y?z递归地使用三元运算符的返回类型定义的.从这个定义来看,对我而言,计算a是否std::common_type<X,Y>是关联的,即是否是,这一点并不明显
using namespace std;
static_assert( is_same<common_type< X, common_type<Y,Z>::type >::type,
common_type< common_type<X,Y>::type, Z >::type>::value, "" );
Run Code Online (Sandbox Code Playgroud)
不会抛出一个编译时错误,所有类型X,Y并Z为其is_same<...>表达是有效的.
请注意,我不是在问
static_assert( is_same<common_type<X,Y>::type,
common_type<Y,X>::type>::value, "" );
Run Code Online (Sandbox Code Playgroud)
永远都会开火.显然不会.以上是一个完全不同的问题.
另请注意,std::common_typeC++ 14 中的规范略有变化,并且可能会在C++中再次发生变化17.因此,对于不同版本的标准,答案可能会有所不同.
Cás*_*nan 11
这在MinGW-w64(gcc 4.9.1)上失败了.VS2013和(感谢Baum mit Augen)在gcc5.2或clang 3.7上使用libc ++也失败了.
#include <type_traits>
using namespace std;
struct Z;
struct X{operator Z();};
struct Y{operator X();};
struct Z{operator Y();};
static_assert( is_same<common_type<X,Y>::type,
common_type<Y,X>::type>::value, "" ); // PASS
static_assert( is_same<common_type<X,Z>::type,
common_type<Z,X>::type>::value, "" ); // PASS
static_assert( is_same<common_type<Y,Z>::type,
common_type<Z,Y>::type>::value, "" ); // PASS
static_assert( is_same<common_type< X, common_type<Y,Z>::type >::type,
common_type< common_type<X,Y>::type, Z >::type>::value, "" ); // FAIL...
Run Code Online (Sandbox Code Playgroud)
#include <type_traits>
struct T2;
struct T1 {
T1(){}
T1(int){}
operator T2();
};
struct T2 {
operator int() { return 0; }
};
struct T3 {
operator int() { return 0; }
};
T1::operator T2() { return T2(); }
using namespace std;
using X = T1;
using Y = T2;
using Z = T3;
int main()
{
true?T2():T3(); // int
static_assert(std::is_same<std::common_type_t<T2,
T3>,
int>::value,
"Not int");
true?T1():(true?T2():T3()); // T1
static_assert(std::is_same<std::common_type_t<T1,
std::common_type_t<T2,
T3>>,
T1>::value,
"Not T1");
// -----------------------------------------
true?T1():T2(); // T2
static_assert(std::is_same<std::common_type_t<T1,
T2>,
T2>::value,
"Not T2");
true?(true?T1():T2()):T3(); // int
static_assert(std::is_same<std::common_type_t<std::common_type_t<T1,
T2>,
T3>,
int>::value,
"Not int");
// -----------------------------------------
static_assert( is_same<common_type_t< X, common_type_t<Y,Z> >,
common_type_t< common_type_t<X,Y>, Z > >::value,
"Don't match");
}
Run Code Online (Sandbox Code Playgroud)
哎哟! 这里的心理体操伤到了我的头脑,但是我想出了一个无法编译的案例,用gcc 4.9.2打印"不匹配",并在ideone上打印 "C++ 14"(gcc 5.1).现在,这是否符合要求是另一回事......
现在声称是类类型,std::common_type_t<X, Y>应该是X或者Y,但我已经强制std::common_type_t<T2, T3>转换为int.
请尝试与其他编译器,让我知道会发生什么!