C++ std::用户定义类型的公共类型特征
自C++11以来,引入了类型traitC++ std::用户定义类型的公共类型特征,c++,templates,c++11,c++14,typetraits,C++,Templates,C++11,C++14,Typetraits,自C++11以来,引入了类型traitstd::common_typestd::common_type确定其所有模板参数之间的公共类型。在C++14中,还引入了它的助手类型std::common_type_t,以便使使用std::common_type类型特征的代码更短 std::common_type在重载算术运算符中特别有用,例如 template<typename T1, typename T2> std::common_type_t<T1, T2> operato
std::common_type
std::common_type
确定其所有模板参数之间的公共类型。在C++14中,还引入了它的助手类型std::common_type_t
,以便使使用std::common_type
类型特征的代码更短
std::common_type
在重载算术运算符中特别有用,例如
template<typename T1, typename T2>
std::common_type_t<T1, T2> operator+(T1 const &t1, T2 const &t2) {
return t1 + t2;
}
Q:我如何使
std::common_type
trait与用户定义的类型一起工作?根据标准草案§20.13.2标题概要[meta.type.synop](强调内容):
一个程序的行为,它为任何一个
除非另有规定,否则本子条款中定义的模板未定义
指定的
因此,为type_trait
添加专门化可能会导致未定义的行为,除非在标准中的其他地方有一个特定类型trait的措辞取代了上面显示的措辞。幸运的是,在表60-其他转换中:
有这样的措辞:
如果至少有一个模板参数,程序可以专门化此特性
在专用化中,是用户定义的类型。[注:如
当只需要显式转换时,需要专门化
在模板参数中。-结束注释]
这意味着,std::common_type
类型trait的专门化至少有一个用户定义的类型是完全允许的。事实上,如果你看一下§20.15.4.3普通_类型的专门化[time.traits.Specializations],你会发现STL已经为用户定义的类型std::chrono::duration
和std::chrono::time_point
定义了std::chrono::time_类型的专门化
因此,对于用户定义的类型,使通用类型
起“作用”的正确方法是为这些特定类型提供it的专门化,例如
struct A {};
struct B {};
namespace std {
template<>
struct common_type<A, B> {
using type = A;
};
}
struct A{};
结构B{};
名称空间标准{
模板
结构公共类型{
使用类型=A;
};
}
在上面的代码示例中,我们指定A
和B
之间的公共类型为A
struct A {};
struct B {};
namespace std {
template<>
struct common_type<A, B> {
using type = A;
};
}