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

WAR*_*ead 3 c++ templates casting typecasting-operator

如果我有模板功能

template<class T, class U>
T foo (U a);
Run Code Online (Sandbox Code Playgroud)

如何检查类的对象是否U可以类型转换为对象T

那就是如果该类U具有成员函数

operator T(); // Whatever T maybe
Run Code Online (Sandbox Code Playgroud)

或者类T有一个构造函数

T(U& a); //ie constructs object with the help of the variable of type U
Run Code Online (Sandbox Code Playgroud)

son*_*yao 7

您可以使用std :: is_convertible(自C++ 11起):

template<class T, class U>
T foo (U a) {
    if (std::is_convertible_v<U, T>) { /*...*/ }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

请注意,这is_convertible_v是自C++ 17以来添加的,如果您的编译器仍然不支持它,您可以使用它std::is_convertible<U, T>::value.