如何用初始化列表构造std :: array对象?

时间:2011-08-01 02:18:49

标签: c++ arrays initializer-list c++11

  

可能重复:
  How do I initialize a member array with an initializer_list?

您可以使用初始化列表构建一个std :: array:

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

3 个答案:

答案 0 :(得分:28)

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<>的确切聚合结构未指定,因此您需要希望它适用于大多数实现。

答案 1 :(得分:25)

由于std::array是一个包含聚合的结构(它本身不是聚合,并且没有带std::initializer_list的构造函数),因此可以初始化结构中的基础聚合使用双括号语法的初始化列表如下:

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

请注意,这不是使用std::initializer_list ...这只是使用C ++初始值设定项列表来初始化std::array的可公开访问的数组成员。

答案 2 :(得分:10)

std::array没有带std::initializer_list的构造函数。这是一件好事,因为初始化列表可能大于数组的固定大小。

您可以通过测试初始化​​程序列表不大于数组的大小来初始化它,然后将初始化程序列表的元素复制到elems成员std::array std::copy