Alex Rivera | Logout

Check if template argument is inherited from class

Asked 2011-02-22T21:30:35.320
18

I want to check if the type given to a template is inherited from a base class in my project.

It should work like one would expect it from the following example:

template< class T : public CBaseClass >
  • Is it possible to do this with templates, if not, how else can I do it?
Edit
Report

1 Answer

14

Following an example from Stroustrup:

template<class Test, class Base>
struct AssertSameOrDerivedFrom {
  AssertSameOrDerivedFrom() { &constraints; }
public:
  static void constraints() {
    Test *pd = 0;
    Base *pb = pd;
  }
};

template<class T>
struct YourClass {
  YourClass() {
    AssertSameOrDerivedFrom<T, CBaseClass>();
  }
};

In C++0x, this becomes:

template<class T>
struct YourClass {
  static_assert(std::is_base_of<CBaseClass, T>::value);
};
answered 2011-02-22T22:13:45.040

Your Answer