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

时间:2016-10-17 08:54:38

标签: c++ templates

class Y; //not really relevant

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

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

  X();
}

我想用array作为参数调用array []的每个元素的构造函数。我怎么能以漂亮的方式做到这一点? C ++ 14甚至17对我来说都没问题。

2 个答案:

答案 0 :(得分:2)

没有&#34;很好&#34;或者使用C数组(甚至std::array)进行简单的方法。

如果您改为使用std::vector,则可以非常轻松地使用它。它有constructor,允许您设置大小传递所有元素的默认值:

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

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

答案 1 :(得分:2)

几种方法之一:

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

相关问题