要检查是否可以将课程打入另一个

To Check if a class can be typecast to another

本文关键字:程打入 另一个 检查 是否      更新时间:2023-10-16

如果我有模板函数

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

您可以使用std :: is_convertible(因为C 11):

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

请注意,添加了is_convertible_v,因为C 17,如果您的编译器仍然不支持它,则可以使用std::is_convertible<U, T>::value