C++ c++;检查模板参数是否派生自某个基类
如何检查模板参数是否派生自某个基类?因此,我确信可以调用函数Do:C++ c++;检查模板参数是否派生自某个基类,c++,templates,inheritance,C++,Templates,Inheritance,如何检查模板参数是否派生自某个基类?因此,我确信可以调用函数Do: template<typename Ty1> class MyClass { ... void MyFunction(); }; template<typename Ty1> void MyClass<Ty1>::MyFunction() { Ty1 var; var.Do(); } 模板类MyClass { ... void MyFunction(); }; 模板无效
template<typename Ty1> class MyClass
{
...
void MyFunction();
};
template<typename Ty1> void MyClass<Ty1>::MyFunction()
{
Ty1 var;
var.Do();
}
模板类MyClass
{
...
void MyFunction();
};
模板无效MyClass::MyFunction()
{
ty1var;
变量Do();
}
不要这样做。如果方法Do()
在作为Ty1
参数提供的类中不存在,它将无法编译
模板是的一种形式:类的能力不是由它从哪个接口继承而来,而是由它实际公开的功能决定的
这样做的好处是,您的模板可以被任何具有合适的
Do()
方法的类使用,而不管它来自何处或它有什么基础。您可以使用标准类型trait is\u base\u实现这一点。看看这个例子:
#include <iostream>
#include <type_traits>
using namespace std;
class Base {
public:
void foo () {}
};
class A : public Base {};
class B : public Base {};
class C {};
void exec (false_type) {
cout << "your type is not derived from Base" << endl;
}
void exec (true_type) {
cout << "your type is derived from Base" << endl;
}
template <typename T>
void verify () {
exec (typename is_base_of<Base, T>::type {});
}
int main (int argc, char** argv) {
verify<A> ();
verify<B> ();
verify<C> ();
return 0;
}
标签发送不是有点多余吗?
your type is derived from Base
your type is derived from Base
your type is not derived from Base