使用相同的构造函数参数初始化所有元素或 std::array

Ale*_*nik 7 c++ templates

我想知道是否可以std::array使用隐式删除的默认构造函数初始化对象,而不先知道数组的大小,因为它是模板参数,因此失去了使用初始化列表的可能性。代码如下,它以打破“调用的隐式删除默认的构造函数std::array<A, 3UL>

struct A {
  A (int b, int c) : mb(b), mc(c) { }
  int mb;
  int mc;
};

template <size_t NR_A>
struct B {
  B (int b, int c) : 
    // <- how to initialize mAs here?
  { }
  std::array<A, NR_A> mAs;
};

B<3> inst(1,1);
Run Code Online (Sandbox Code Playgroud)

编辑:我想所有的初始化A的的mAsA{1,1}

Pas*_* By 7

您可以使用委托构造函数和包扩展

struct A {
    A(int b, int c) : b(b), c(c) { }
    A(const A&) = delete;
    A(A&&) = delete;
    int b;
    int c;
};

template <size_t N>
struct B {
  B (int b, int c) : B(b, c, std::make_index_sequence<N>{}) {}

  template<size_t... Is>
  B (int b, int c, std::index_sequence<Is...>) :
    arr{(Is, A{b, c})...}
  {}

  std::array<A, N> arr;
};
Run Code Online (Sandbox Code Playgroud)

居住

请注意,如果删除了移动和复制构造函数,则这仅在 C++17 之后有效。


眠りネ*_*ネロク 4

对于 C++11 和 C++14(即:C++17 之前的版本),您想要的都可以通过模板元编程来实现。

您可以声明以下辅助类模板 ,array_maker<>它具有一个递归调用自身的static成员函数模板:make_array

template<typename T, std::size_t N, std::size_t Idx = N>
struct array_maker {
    template<typename... Ts>
    static std::array<T, N> make_array(const T& v, Ts...tail) {
        return array_maker<T, N, Idx-1>::make_array(v, v, tail...);
    }
};
Run Code Online (Sandbox Code Playgroud)

然后,将此类模板专门化为Idx等于 的情况1,即:递归的基本情况:

template<typename T, std::size_t N>
struct array_maker<T, N, 1> {
    template<typename... Ts>
    static std::array<T, N> make_array(const T& v, Ts... tail) {
        return std::array<T, N>{v, tail...};
    }
};
Run Code Online (Sandbox Code Playgroud)

最后,它可以在模板的构造函数中以这种方式使用:

template <size_t NR_A>
struct B {
  B (int b, int c) : mAs{array_maker<A, NR_A>::make_array(A{b,c})}
  {}    
  std::array<A, NR_A> mAs;
};
Run Code Online (Sandbox Code Playgroud)