【问题标题】:C++ Class inheritance and templatesC++ 类继承和模板
【发布时间】:2013-11-28 12:18:57
【问题描述】:

我想在我的 C++ 程序中编写如下内容:

class A {
 public:
   void a();
}

template <class B extends A>
class C {
 B instance;
}

这可能吗?换句话说:C++ 允许我说模板中的类是其他东西的子类吗?

【问题讨论】:

  • @LuchianGrigore:类似,但那是关于函数的,这是关于类的。解决方案可能略有不同(例如 enable_if 是那里的最佳答案,但在这里没有多大意义)。

标签: c++ templates inheritance


【解决方案1】:

定义一个名为extends(这只是一个糖衣名称)的元函数:

template<typename D, typename B>
using extends = std::is_base_of<B,D>;

然后将你的类定义为:

template <class B>
class C 
{
   //here you can check it, and generate your own error message!
   static_assert(extends<B,A>(), 
                "Constraint Violation: B doesn't derive from A.");

   B instance;
};

或者,你也可以这样写:

//define it a bit differently now!
template<typename D, typename B>
using extends = typename std::enable_if<std::is_base_of<B,D>::value>::type;

template <class B, class Unused=extends<B,A>>
class C 
{
      B instance;
};

但在这种情况下,您没有机会生成自己的错误消息。编译器可以随意向您抛出任何可能难以理解的错误消息

无论如何,您可能意识到您可以直接使用std::is_base_of&lt;&gt;。但是,如果您正在寻找糖衣name,那么extends 听起来不错!

【讨论】:

  • 你可以从第二个例子中删除Unused
【解决方案2】:

并不是直接的。但是您可以将static_asserttype_traits 一起使用,如下所示:

static_assert(is_base_of<A,B>::value, "C<B> requires B:A");

例如,您可以将其放在构造函数中,如果不满足要求,它将无法编译。请注意,这都是 C++11 的东西,但它早在 Boost 中就存在了,或者如果你真的卡住了,你可以自己编写代码(它不需要语言支持)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    相关资源
    最近更新 更多