2

如何专门化一个类模板,以便模板参数可以是类型:指向特定类的指针或指向该特定类型的派生类的指针?不使用Boost可以做到吗?

可能重复: 仅接受某些类型的 C++ 模板

我只是想知道答案是否相同,即使我使用的是指向实例的指针。

4

2 回答 2

5

您可以将您的类专门用于指针,然后std::is_base_of使用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");
};

看到它在行动。两者都是 C++11 特性std::is_base_ofstatic_assert因此不需要 Boost。

如果由于某种原因你不喜欢static_assert,你可以这样做enable_if

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>
{
  // ...
};
于 2013-02-04T09:42:43.173 回答
1

一种基于某些谓词而不是模式的特化技术是使用额外的默认参数。

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
};

您所需要的只是一个适当的谓词。在这种情况下,std::is_base_of似乎很合适。它也有一个增强的实现。

于 2013-02-04T09:51:00.927 回答