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?
Asked
Active
Viewed 2,175 times
2
-
2http://stackoverflow.com/questions/3175219/restrict-c-template-parameter-to-subclass – Jason LeBrun Apr 14 '11 at 02:29
-
2possible 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 Answers
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
-
2Could also put that into the template parameters: `template
::value>::type>`. – Xeo Apr 14 '11 at 02:35 -
Yes, you could, but then your template parameter list quickly gets unwieldy. – James McNellis Apr 14 '11 at 02:38
-
Personally I find `static B* check = (T*) 0` clear enough. No need to include Boost for just this. – MSalters Apr 14 '11 at 09:04