首页 > 解决方案 > 通过代码构造 std::array 并初始化元素对象

问题描述

我想初始化我的数组项,同时避免不必要的实例和副本(类似于这个问题:initialize std::array without copying/moving elements)。

初始化列表确实适用于少量对象。

位我想通过代码片段来做到这一点,因为我的数组有数百个项目......

我怎样才能做到这一点?

#include <array>
#include <iostream>

class mytype {
public:
    int a;
    mytype() : a(0) {}
    mytype(int a) : a(a) {}
};

int main() {
    // explict constructor calls to instantiate objects does work
    std::array<mytype, 2> a = { { mytype(10), mytype(20) } };
    std::cout << a[0].a;  // 10

    // I want to do something like this - what does not work of course
    std::array<mytype, 2> b = { { for (i = 0, i++, i < 2) mtype(10 * i); } };
}

标签: c++initializationc++14stdarray

解决方案


这通常通过一对模板来完成:

namespace detail {
    template<std::size_t... Idx>
    auto make_mytype_array(std::index_sequence<Idx...>) {
        return std::array<mytype, sizeof...(Idx)>{{
            mytype(10 * Idx)...
        }};
    }
}

template<std::size_t N>
auto make_mytype_array() {
    return detail::make_mytype_array(make_index_sequence<N>{});
}

以上是一对实用程序免费函数,但如果需要,可以折叠到类中。如果您需要的不仅仅是像这样的表达式10*i,那么可以将 lambda 作为另一个参数传递(模板化为一般的“可调用”)。使用复制省略,这将全部折叠为结果数组对象的直接初始化。


推荐阅读