简体   繁体   English

C ++类继承和模板

[英]C++ Class inheritance and templates

I would like to write in my C++ program something like: 我想在我的C ++程序中写一些类似于:

class A {
 public:
   void a();
}

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

Is this possible? 这可能吗? In other words: does C++ allow me to say that the class within a template is a subclass of something else? 换句话说:C ++是否允许我说模板中的类是其他东西的子类?

Define a meta-function called extends (which is just a sugar-coated name) as: 定义一个名为extends (它只是一个糖涂层名称)的元函数:

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

Then define your class as: 然后将您的类定义为:

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

Or, you can write this instead: 或者,你可以写这个:

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

But in this case, you don't have opportunity to generate your own error message. 但在这种情况下,您没有机会生成自己的错误消息。 The compiler is free to throw any error message at you which may be difficult to comprehend. 编译器可以随意向您抛出任何可能难以理解的错误消息

Anyway, you probably realize you can use std::is_base_of<> directly. 无论如何,你可能意识到你可以直接使用std::is_base_of<> But if you're looking for sugar-coated name , then extends sounds good! 但如果你正在寻找糖衣名称 ,那么extends听起来不错!

Not really in a direct way. 不是直接的。 But you can use static_assert with type_traits , like this: 但是你可以将static_asserttype_traits一起使用,如下所示:

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

You can put that in your constructor for example, then it will fail to compile if the requirement is not satisfied. 例如,您可以将它放在构造函数中,如果不满足要求,则无法编译。 Note that this is all C++11 stuff, but it exists in Boost long before that, or you can code it up yourself if you're really stuck (it doesn't require language support). 请注意,这是所有C ++ 11的东西,但它在很久之前就存在于Boost中,或者你可以自己编写代码,如果你真的被卡住了(它不需要语言支持)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM