如果我有模板功能
template<class T, class U>
T foo (U a);
如何检查类U
的对象是否可以类型转换为对象T
即如果类U
具有成员函数
operator T(); // Whatever T maybe
或者类T
有一个构造函数
T(U& a); //ie constructs object with the help of the variable of type U
答案 0 :(得分:7)
您可以使用std::is_convertible(自C ++ 11起):
template<class T, class U>
T foo (U a) {
if (std::is_convertible_v<U, T>) { /*...*/ }
// ...
}
请注意,自C ++ 17以来添加了is_convertible_v
,如果您的编译器仍然不支持它,则可以改为使用std::is_convertible<U, T>::value
。