可能重复:
How do I initialize a member array with an 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'};发布于 2011-08-01 04:22:16
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<>的确切聚合结构还没有指定,所以您需要希望它在大多数实现上都能工作。
发布于 2011-08-01 03:57:52
由于std::array是包含聚合的结构(它本身不是聚合本身,并且没有接受std::initializer_list的构造函数),所以可以使用一个双大括号语法初始化结构内的底层聚合,如下所示:
std::array<int, 4> my_array = {{1, 2, 3, 4}};注意,这不是使用std::initializer_list ..。这只是使用C++初始化程序列表来初始化std::array的可公开访问的数组成员。
发布于 2011-08-01 03:09:14
std::array没有接受std::initializer_list的构造函数。这是一件好事,因为初始化程序列表可以大于数组的固定大小。
您可以通过测试初始化程序列表的大小不大于数组的大小来初始化它,然后使用elems将初始化程序列表的元素复制到std::array的std::copy成员。
https://stackoverflow.com/questions/6893700
复制相似问题