【发布时间】:2016-07-31 02:25:02
【问题描述】:
从 C++11 开始,引入了类型特征 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;
}
如果它的模板参数内置在类型中(例如,int、double),它就可以正常工作。但是,如果我将模板参数作为用户定义的类型提供给它,我似乎不起作用,例如,
struct A {};
struct B {};
std::common_type_t<A, B> // doesn't work
问:如何使std::common_type trait 与用户定义的类型一起使用?
【问题讨论】:
标签: c++ templates c++11 c++14 typetraits