使用相同的构造函数参数初始化所有元素或 std::array [英] Initialize all elements or std::array with the same constructor arguments

查看:26
本文介绍了使用相同的构造函数参数初始化所有元素或 std::array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wondering if it's possible to initialize a std::array of objects with an implicitly deleted default constructor, without knowing a priori the size of the array because it's a template argument and so having lost the possibility of using an initializer list. Code follows, it breaks with a "call to implicitly-deleted default constructor of 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);

我想将 mAs 的所有 A 初始化为 A{1,1}

edit: I'd like to initialize all the A's of mAs to A{1,1}

推荐答案

对于 C++11 和 C++14(即:C++17 之前的)你想要的东西都可以通过模板元编程来实现.

For both C++11 and C++14 (i.e.: pre-C++17) what you want can be achieved by means of template metaprogramming.

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

You could declare the following helper class template, array_maker<>, which has a static member function template, make_array, that calls itself recursively:

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...);
    }
};

然后,为Idx等于1的case特化这个类模板,即:递归的base case:

Then, specialize this class template for the case Idx equal to 1, i.e.: the base case of the recursion:

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...};
    }
};

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

Finally, it can be used in the constructor of your template this way:

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;
};

这篇关于使用相同的构造函数参数初始化所有元素或 std::array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆