简体   繁体   English

使用可变参数模板模拟多个 inheritance

[英]Using variadic templates to emulate multiple inheritance

I'm not entirely sure if this is possible or what syntax I would need to employ if it is, but I want to make a class that publicly derives from all of the classes provided in the variadic arguments so that I could derive from that single class and thereby derive from all the classes that were supplied to it.我不完全确定这是否可行,或者如果可行的话我需要使用什么语法,但我想制作一个 class 公开派生自可变参数 arguments 中提供的所有类,以便我可以从该单一派生class,从而派生自提供给它的所有类。

What I am wanting to be able do is declare something like:我想要做的是声明如下内容:

class MyClass : public InheritFrom<ClassA, ClassB,  ,,,> {
};

So that the InheritFrom template class effectively publicly derives from all of the classes listed.因此 InheritFrom 模板 class 有效地公开派生自所有列出的类。 In my use case, each class provided will have a default constructor, so no special constructors will have to be called.在我的用例中,提供的每个 class 都有一个默认构造函数,因此不需要调用特殊的构造函数。

What I had tried to do was this:我试图做的是:

template <class A, class ... Args> class InheritFrom : public A, public InheritFrom<Args...> {
...
};

template <class A> class InheritFrom : public A {
...
};

And effectively turn what would otherwise have been a multiple inheritance into a single inheritance heirarchy, but the compiler complains about the second InheritFrom declaration, which was supposed to be a specialization where only one class is given, as being a redeclaration with one parameter.并有效地将本来是多个 inheritance 的东西变成单个 inheritance 层次结构,但编译器抱怨第二个InheritFrom声明,它应该是一个专门化,其中只给出一个 class,因为它是一个带有一个参数的重新声明。 There will ultimately be much more detail within the body of each of these classes, but for now I'm just trying to figure out how to get the syntax right.这些类中的每一个的主体最终都会有更多的细节,但现在我只是想弄清楚如何获得正确的语法。

In c++17 you just need to expand the pack, nothing more to it.在 c++17 你只需要扩展包,仅此而已。

#include<iostream>
#include<type_traits>

template <class ...T> class InheritFrom : public T... {
};

struct Foo {};

struct Bar {};

struct Baz : InheritFrom<Foo, Bar> {};

int main(){
    std::cout << std::is_base_of_v<Foo, Baz> << std::is_base_of_v<Bar, Baz>;
}

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

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