除非我弄错了,否则应该可以通过以下方式创建一个std:array:
std::array<std::string, 2> strings = { "a", "b" };
std::array<std::string, 2> strings({ "a", "b" });
Run Code Online (Sandbox Code Playgroud)
然而,使用GCC 4.6.1我无法使其中任何一个工作.编译器简单地说:
expected primary-expression before ',' token
Run Code Online (Sandbox Code Playgroud)
然而初始化列表与std :: vector一起工作正常.那是哪个呢?我错误地认为std :: array应该接受初始化列表,还是让GNU标准C++库团队搞错了?
考虑功能:
template<typename T>
void printme(T&& t) {
for (auto i : t)
std::cout << i;
}
Run Code Online (Sandbox Code Playgroud)
或任何其他期望一个参数具有begin()/ end()启用类型的函数.
以下为什么违法?
printme({'a', 'b', 'c'});
当所有这些都合法时:
printme(std::vector<char>({'a', 'b', 'c'}));
printme(std::string("abc"));
printme(std::array<char, 3> {'a', 'b', 'c'});
Run Code Online (Sandbox Code Playgroud)
我们甚至可以这样写:
const auto il = {'a', 'b', 'c'};
printme(il);
Run Code Online (Sandbox Code Playgroud)
要么
printme<std::initializer_list<char>>({'a', 'b', 'c'});
Run Code Online (Sandbox Code Playgroud) 您可以使用初始化列表构建一个std :: array:
std::array<int, 3> a = {1, 2, 3}; // works fine
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试从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, …Run Code Online (Sandbox Code Playgroud)