我有一个类,它是另一个实现所需功能的类的包装类(充当通用接口)。所以我的代码看起来像这样。

template<typename ImplemenationClass> class WrapperClass {
// the code goes here
}

现在,我如何确保 ImplementationClass 只能从一组类派生,类似于java的泛型

<? extends BaseClass>

句法?

有帮助吗?

解决方案

它很冗长,但你可以这样做:

#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_base_of.hpp>

struct base {};

template <typename ImplementationClass, class Enable = void>
class WrapperClass;

template <typename ImplementationClass>
class WrapperClass<ImplementationClass,
      typename boost::enable_if<
        boost::is_base_of<base,ImplementationClass> >::type>
{};

struct derived : base {};
struct not_derived {};

int main() {
    WrapperClass<derived> x;

    // Compile error here:
    WrapperClass<not_derived> y;
}

这需要一个对标准有良好支持的编译器(最新的编译器应该没问题,但旧版本的 Visual C++ 则不行)。欲了解更多信息,请参阅 Boost.Enable_If 文档.

正如 Ferruccio 所说,一个更简单但功能较弱的实现:

#include <boost/static_assert.hpp>
#include <boost/type_traits/is_base_of.hpp>

struct base {};

template <typename ImplementationClass>
class WrapperClass
{
    BOOST_STATIC_ASSERT((
        boost::is_base_of<base, ImplementationClass>::value));
};

其他提示

从目前的情况来看,除了通过评论或者第三方解决方案之外,没有什么好的办法。升压提供了 概念检查库 为此,我认为 gcc 也有一个实现。概念位于 C++0x 改进列表中,但我不确定您是否可以指定子类型 - 它们更多的是“必须支持这些操作”,这是(大致)等效的。

编辑: 维基百科有这个 部分 关于 C++0x 中的概念,这比提案草案更容易阅读。

Stoustrup 自己关于该主题的话.

基本上是一个小类,您可以在某个地方实例化它,例如模板化类的构造函数。

template<class T, class B> struct Derived_from {
    static void constraints(T* p) { B* pb = p; }
    Derived_from() { void(*p)(T*) = constraints; }
};
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top