c ++检查模板参数是否来自某个基类

udu*_*uck 2 c++ inheritance templates

如何检查我的模板参数是否来自某个基类?所以我确信可以调用函数Do:

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

template<typename Ty1> void MyClass<Ty1>::MyFunction()
{
  Ty1 var;
  var.Do();
}
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 7

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

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

优点是任何类都可以使用合适的Do()方法使用您的模板,无论它来自何处或具有何种基础.


Art*_*zuk 6

您可以使用标准类型特征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;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

your type is derived from Base
your type is derived from Base
your type is not derived from Base
Run Code Online (Sandbox Code Playgroud)