Reputation: 1599
How can I specialize a class template so that the template parameters can be of type : a pointer to a particular class or a pointer to the derived class of that particular type? Is it possible to do it without using Boost?
Possible Duplicate of: C++ templates that accept only certain types
I just wanted to know whether the answer is same even if I am using a pointer to the instances .
Upvotes: 2
Views: 539
Reputation: 110768
You could specialize your class for pointers and then use std::is_base_of
with a static_assert
:
template <typename T>
class foo;
template <typename T>
class foo<T*>
{
static_assert(std::is_base_of<Base, T>::value, "Type is not a pointer to type derived from Base");
};
See it in action. Both std::is_base_of
and static_assert
are C++11 features so no Boost is required.
If for some reason you don't like static_assert
, you could do it the enable_if
way:
template <typename T, typename Enable = void>
class foo;
template <typename T>
class foo<T*, typename std::enable_if<is_base_of<Base, T>::value>::type>
{
// ...
};
Upvotes: 5
Reputation: 234654
A technique for having specializations based on some predicate instead of a pattern is to use an extra defaulted parameter.
template <typename T, bool = predicate<T>::value>
class foo {
// here is the primary template
};
template <typename T>
class foo<T, true> {
// here is the specialization for when the predicate is true
};
All you need is a proper predicate. In this case, std::is_base_of
seems to fit. There is a boost implementation of it too.
Upvotes: 1