如何用初始值设定项列表构造std::数组对象

How to construct std::array object with initializer list?

本文关键字:std 列表 数组 对象 何用初      更新时间:2023-10-16

可能重复:
如何使用initializer_list初始化成员数组?

您可以使用初始值设定项列表构造一个std::数组:

std::array<int, 3> a = {1, 2, 3};  // works fine

然而,当我试图将std::initializer_list构造为类中的数据成员或基对象时,它不起作用:

#include <array>
#include <initializer_list>
template <typename T, std::size_t size, typename EnumT>
struct enum_addressable_array : public std::array<T, size>
{
    typedef std::array<T, size> base_t;
    typedef typename base_t::reference reference;
    typedef typename base_t::const_reference const_reference;
    typedef typename base_t::size_type size_type;
    enum_addressable_array(std::initializer_list<T> il) : base_t{il} {}
    reference operator[](EnumT n)
    {
        return base_t::operator[](static_cast<size_type>(n));
    }
    const_reference operator[](EnumT n) const
    {
        return base_t::operator[](static_cast<size_type>(n));
    }
};
enum class E {a, b, c};
enum_addressable_array<char, 3, E> ea = {'a', 'b', 'c'};

gcc 4.6:错误

test.cpp: In constructor 'enum_addressable_array<T, size, EnumT>::enum_addressable_array(std::initializer_list<T>) [with T = char, unsigned int size = 3u, EnumT = E]':
test.cpp:26:55:   instantiated from here
test.cpp:12:68: error: no matching function for call to 'std::array<char, 3u>::array(<brace-enclosed initializer list>)'
test.cpp:12:68: note: candidates are:
include/c++/4.6.1/array:60:12: note: std::array<char, 3u>::array()
include/c++/4.6.1/array:60:12: note:   candidate expects 0 arguments, 1 provided
include/c++/4.6.1/array:60:12: note: constexpr std::array<char, 3u>::array(const std::array<char, 3u>&)
include/c++/4.6.1/array:60:12: note:   no known conversion for argument 1 from 'std::initializer_list<char>' to 'const std::array<char, 3u>&'
include/c++/4.6.1/array:60:12: note: constexpr std::array<char, 3u>::array(std::array<char, 3u>&&)
include/c++/4.6.1/array:60:12: note:   no known conversion for argument 1 from 'std::initializer_list<char>' to 'std::array<char, 3u>&&'

我如何让它工作,以便我的包装类可以用初始化器列表初始化,例如:

enum_addressable_array<char, 3, E> ea = {'a', 'b', 'c'};

std::array<>没有接受std::initializer_list<>(初始值设定项列表构造函数(的构造函数,也没有特殊的语言支持将std::initializer_list<>传递给类的构造函数以使其工作。所以失败了。

要使其工作,派生类需要捕获所有元素,然后转发它们,构造函数模板:

template<typename ...E>
enum_addressable_array(E&&...e) : base_t{{std::forward<E>(e)...}} {}

注意,在这种情况下您需要{{...}},因为省略大括号(在您的情况下省略大括号(在那个地方不起作用。它只允许在T t = { ... }形式的声明中使用。由于std::array<>由嵌入原始数组的结构组成,因此需要两级大括号。不幸的是,我认为std::array<>的确切聚合结构是未指定的,所以您需要希望它能在大多数实现中工作。

由于std::array是一个包含聚合的结构(它本身不是聚合,也没有采用std::initializer_list的构造函数(,因此可以使用双大括号语法使用初始化器列表初始化结构内部的底层聚合,如下所示:

std::array<int, 4> my_array = {{1, 2, 3, 4}};

请注意,这不是在使用std::initializer_list。。。这只是简单地使用C++初始化器列表来初始化CCD_ 12的可公开访问的数组成员。

std::array没有接受std::initializer_list的构造函数。这是一件好事,因为初始值设定项列表可以大于数组的固定大小。

您可以通过测试初始化器列表不大于数组的大小来初始化它,然后用std::copy将初始化器列表的元素复制到std::arrayelems成员。