问题描述
|
我有一个旨在与某种类型的参数一起使用的类。有什么方法可以强制让template参数成为某种类型的子类的指针?
解决方法
#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!
}
enable_if
实用程序和is_base_of
类型特征是C ++ 0x标准库的一部分,但在Boost中也都可用。