检查一个类是否可以转换为另一个类

时间:2016-12-16 13:21:33

标签: c++ templates casting typecasting-operator

如果我有模板功能

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

1 个答案:

答案 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

相关问题