自從C++ 11引入類型特徵std::common_type
以來。 std::common_type
確定所有模板參數之間的通用類型。在C++ 14中,爲了使使用std::common_type
類型特徵的代碼更短,還引入了幫助類型std::common_type_t
。用戶定義類型的std :: common_type trait
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
Q:我怎樣才能讓std::common_type
與用戶定義類型特質的工作?