c – 检查某个类是否可以转换为另一个类
发布时间:2020-12-16 10:04:47 所属栏目:百科 来源:网络整理
导读:如果我有模板功能 templateclass T,class UT foo (U a); 如何检查是否可以将类U的对象类型转换为对象T. 那就是如果U类具有成员函数 operator T(); // Whatever T maybe 或者类T有一个构造函数 T(U a); //ie constructs object with the help of the variable
如果我有模板功能
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>) { /*...*/ } // ... } 请注意,从C 17开始添加is_convertible_v,如果编译器仍然不支持它,则可以使用std :: is_convertible< U,T> :: value. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |