uduck
uduck

Reputation: 149

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

How can I check whether my template parameters are derived from a certain base class? So that I am sure that the function Do can be called:

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

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

Upvotes: 2

Views: 1752

Answers (2)

Quentin
Quentin

Reputation: 63114

Don't. If the method Do() doesn't exist in the class provided as an argument for Ty1, it will simply not compile.

Templates are a form of duck typing : the abilities of a class are not determined by what interface it inherits from, but by what functionality it actually exposes.

The advantage is that your template can then be used by any class with a suitable Do() method, regardless of where it came from or what bases it has.

Upvotes: 7

Artur Pyszczuk
Artur Pyszczuk

Reputation: 1930

You can achieve this using standard type trait is_base_of. Look at the example:

#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;
}

And the output is:

your type is derived from Base
your type is derived from Base
your type is not derived from Base

Upvotes: 7

Related Questions