C++ 将 std::array 与初始化列表一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8192185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using std::array with initialization lists
提问by Chris_F
Unless I am mistaken, it should be possible to create a std:array in these ways:
除非我弄错了,否则应该可以通过以下方式创建 std:array :
std::array<std::string, 2> strings = { "a", "b" };
std::array<std::string, 2> strings({ "a", "b" });
And yet, using GCC 4.6.1 I am unable to get any of these to work. The compiler simply says:
然而,使用 GCC 4.6.1 我无法让其中任何一个工作。编译器简单地说:
expected primary-expression before ',' token
and yet initialization lists work just fine with std::vector. So which is it? Am I mistaken to think std::array should accept initialization lists, or has the GNU Standard C++ Library team goofed?
然而初始化列表与 std::vector 一起工作得很好。那么它是哪个?我错误地认为 std::array 应该接受初始化列表,还是 GNU 标准 C++ 库团队搞砸了?
回答by Nicol Bolas
std::array
is funny. It is defined basically like this:
std::array
很有趣。它的定义基本上是这样的:
template<typename T, int size>
struct std::array
{
T a[size];
};
It is a struct which contains an array. It does not have a constructor that takes an initializer list. But std::array
is an aggregate by the rules of C++11, and therefore it can be created by aggregate initialization. To aggregate initialize the array insidethe struct, you need a second set of curly braces:
它是一个包含数组的结构。它没有接受初始化列表的构造函数。但是std::array
按照 C++11 的规则是一个聚合,因此它可以通过聚合初始化来创建。要在结构内聚合初始化数组,您需要第二组花括号:
std::array<std::string, 2> strings = {{ "a", "b" }};
Note that the standard does suggest that the extra braces can be elided in this case. So it likely is a GCC bug.
请注意,标准确实建议在这种情况下可以省略额外的大括号。所以它可能是一个 GCC 错误。
回答by Joseph
To add to the accepted answer:
添加到接受的答案:
std::array<char, 2> a1{'a', 'b'};
std::array<char, 2> a2 = {'a', 'b'};
std::array<char, 2> a3{{'a', 'b'}};
std::array<char, 2> a4 = {{'a', 'b'}};
all work on GCC 4.6.3 (Xubuntu 12.01). However,
GCC 4.6.3 (Xubuntu 12.01) 上的所有工作。然而,
void f(std::array<char, 2> a)
{
}
//f({'a', 'b'}); //doesn't compile
f({{'a', 'b'}});
the above requires double braces to compile. The version with single braces results in the following error:
以上需要双大括号才能编译。带有单括号的版本会导致以下错误:
../src/main.cc: In function ‘int main(int, char**)':
../src/main.cc:23:17: error: could not convert ‘{'a', 'b'}' from ‘<brace-enclosed initializer list>' to ‘std::array<char, 2ul>'
I'm not sure what aspect of type inference/conversion makes things work this way, or if this is a quirk of GCC's implementation.
我不确定类型推断/转换的哪个方面使事情以这种方式工作,或者这是否是 GCC 实现的一个怪癖。