可能是重复问题:
如何使用初始化列表初始化成员数组?
使用初始化列表可以很好地构造一个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'};
E&& ...e
。(有时候,g++ 告诉我去杀人。) - John McFarlanetemplate<typename ...E, class = decltype(base_t{{std::forward<Args__>(std::declval<Args__>()...)...}}> enum_addressable_array(E&&...e) : base_t{{std::forward<E>(e)...}} {}
(我无法让它正常工作) - alfC= { ... }
初始化。但不需要支持= {{ .. }}
初始化。然而,在成员初始化器的情况下,只有后者才能起作用。但由于不需要支持后者,并且前者仅需要支持= { ... }
语法,因此在成员初始化器的情况下没有可移植的语法。然而,我不了解规范的最新修订。也许他们现在也支持这种情况。 - Johannes Schaub - litb