【问题标题】:Construct std::array and initialize element objects via code通过代码构造 std::array 并初始化元素对象
【发布时间】:2018-12-02 12:57:11
【问题描述】:

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

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

我想通过代码 sn-p 来执行此操作,因为我的数组有数百个项目...

我该怎么做?

#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++ initialization c++14 stdarray


【解决方案1】:

:

#include <array>
#include <utility>
#include <cstddef>

template <typename T, std::size_t... Is>
std::array<T, sizeof...(Is)> to_array(std::index_sequence<Is...>)
{
    return { T(Is*10)... };
}

template <typename T, std::size_t N>
std::array<T, N> to_array()
{
    return to_array<T>(std::make_index_sequence<N>{});
}

int main() 
{
    std::array<mytype, 10> b(to_array<mytype, 10>());
}

DEMO

【讨论】:

    【解决方案2】:

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

    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 作为另一个参数传递(模板化为一般的“可调用”)。使用复制省略,这将全部折叠为结果数组对象的直接初始化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-27
      • 2011-10-17
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      • 2016-02-16
      • 2022-01-22
      相关资源
      最近更新 更多