简体   繁体   English

初始化列表中的模板大小数组初始化,C++

[英]template-size array initialization in initializer list, C++

class Y; //not really relevant

class B
{
  B(Y*);
  //stuff
}

template<int SIZE> class X : public Y
{
  B array[SIZE];

  X();
}

I would like to call constructor of each element of array[] with this as parameter.我想以此为参数调用 array[] 的每个元素的构造函数。 How can I do that in pretty way?我怎么能以漂亮的方式做到这一点? C++14 and even 17 are OK for me. C++14 甚至 17 对我来说都可以。

One of several approaches:几种方法之一:

template <int SIZE>
class X : public Y
{
    B array[SIZE];

    template <std::size_t>
    X* that() { return this; } // don't abuse the comma operator

    template <std::size_t... Is>
    X(std::index_sequence<Is...>) : array{ that<Is>()... } {}

public:
    X() : X(std::make_index_sequence<SIZE>{}) {}
};

DEMO演示

There's no "nice" or simple way of doing it with C arrays (or even std::array ).使用 C 数组(甚至std::array )没有“好”或简单的方法。

You can to it very easily if you change to use a std::vector instead.如果您改为使用std::vector ,则可以非常轻松地使用它。 It has a constructor that allows you to set the size and pass the default value for all elements:它有一个构造函数,允许您设置大小为所有元素传递默认值:

template<int SIZE> class X : public Y
{
    std::vector<B> array;

    X()
        : array(SIZE, B(this))
    {}
};

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

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