Can I specify that template arguments ought to be subclasses of some base class?
I have a c开发者_如何学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?
#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.
精彩评论