c++检查模板参数是否从某个基类派生

c++ check that templates parameters are derived from a certain base class

本文关键字:基类 派生 是否 检查 参数 c++      更新时间:2023-10-16

如何检查模板参数是否从某个基类派生?所以我确信函数Do可以被调用:

template<typename Ty1> class MyClass
{
  ...
  void MyFunction();
}; 
template<typename Ty1> void MyClass<Ty1>::MyFunction()
{
  Ty1 var;
  var.Do();
}

不要。如果方法Do()不存在于作为Ty1参数提供的类中,则它将无法编译。

模板是鸭类型的一种形式:类的能力不是由它继承的接口决定的,而是由它实际暴露的功能决定的。

的优点是,你的模板可以被任何类使用一个合适的Do()方法,不管它来自哪里或它有什么基础。

您可以使用标准类型trait is_base_of来实现这一点。请看下面的例子:

#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