简体   繁体   English

包扩展中的多个 inheritance

[英]Multiple inheritance from a pack expansion

I recently saw this in production code and couldn't quite figure out what it does:我最近在生产代码中看到了这个,但不太明白它的作用:

template <class... Ts>
struct pool : pool_type<Ts>... {
//...
};

I've never seen pack expansion happening for parent classes.我从未见过父类发生包扩展。 Does it just inherit every type passed into the varargs?它只是继承传递给可变参数的每种类型吗?

The parents look like this:父母长这样:

template <class T>
struct pool_type : pool_type_impl<T> {
// ...
};

Does it just inherit every type passed into the varargs?它只是继承传递给可变参数的每种类型吗?

Yes.是的。 It inherits publicly from each of the passed arguments. A simplified version is given below.公开继承了每个通过的 arguments。下面给出了一个简化版本。

From Parameter pack's documentation :参数包的文档

Depending on where the expansion takes place, the resulting comma-separated list is a different kind of list: function parameter list, member initializer list, attribute list, etc. The following is the list of all allowed contexts:根据扩展发生的位置,生成的逗号分隔列表是一种不同类型的列表:function 参数列表、成员初始值设定项列表、属性列表等。以下是所有允许上下文的列表:

  • Base specifiers and member initializer lists :基本说明符和成员初始值设定项列表
    A pack expansion may designate the list of base classes in a class declaration.包扩展可以在 class 声明中指定基类列表

Example例子

struct Person 
{
    Person() = default;
    Person(const Person&)
    {
        std::cout<<"copy constrcutor person called"<<std::endl;
    }
};
struct Name 
{
    Name() = default;
    Name(const Name&)
    {
        std::cout<<"copy constructor Name called"<<std::endl;
    }
};

template<class... Mixins>
//---------------vvvvvvvvv---------->used as list of base classes from which X inherits publicly
class X : public Mixins...
{
public:
//-------------------------------vvvvvvvvvvvvvvvvv---->used as member initializer list
    X(const Mixins&... mixins) : Mixins(mixins)... {}
};
int main()
{
    Person p;
    Name n;
    X<Person, Name> x(p, n); //or even just X x(p, n);  works with C++17 due to CTAD
    return 0;
}

The output of the above program can be seen here :上面程序的 output 可以在这里看到:

copy constrcutor person called
copy constructor Name called
constructor called

Explanation解释

In the above code, the X class template uses a pack expansion to take each of the supplied mixins and expand it into a public base class .在上面的代码中, X class 模板使用pack 扩展来获取每个提供的 mixins 并将其扩展到公共基础 class中。 In other words, we get a list of base classes from which X inherits publicly.换句话说,我们获得了X公开继承的基类列表。 Moreover, we also have a X constructor that copy-initializes each of the mixins from supplied constructor arguments.此外,我们还有一个X构造函数,它从提供的构造函数 arguments 中复制初始化每个混入。

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

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