2

I have a class that is designed to work with a certain type of parameter. Is there any way that I can enforce that the template parameter be a pointer to a subclass of some type?

alexgolec
  • 26,898
  • 33
  • 107
  • 159
  • 2
    http://stackoverflow.com/questions/3175219/restrict-c-template-parameter-to-subclass – Jason LeBrun Apr 14 '11 at 02:29
  • 2
    possible duplicate of [C++: Templates of child classes only](http://stackoverflow.com/questions/5612521/c-templates-of-child-classes-only) – Xeo Apr 14 '11 at 02:30

1 Answers1

8
#include <type_traits>
#include <utility>

struct B { };
struct D : B { };

template <typename T>
struct S {
    typedef typename std::enable_if<std::is_base_of<B, T>::value>::type check;
};

int main()
{
    S<B> x;   // Ok!
    S<D> y;   // Ok!
    S<int> z; // Not ok!
}

The enable_if utility and the is_base_of type trait are part of the C++0x Standard Library, but both available in Boost as well.

James McNellis
  • 348,265
  • 75
  • 913
  • 977