12

Astd::array<T>は基本的に、でラップされたCスタイルの配列structです。sの初期化にstructは中括弧が必要であり、配列の初期化にも中括弧が必要です。したがって、2組の中括弧が必要です。

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

しかし、私が見たサンプルコードのほとんどは、中括弧の1つのペアのみを使用しています。

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

なぜこれが許可され、最初のアプローチと比較してメリットやデメリットがありますか?

4

1 に答える 1

14

The benefit is that you have ... less to type. But the drawback is that you are only allowed to leave off braces when the declaration has that form. If you leave off the =, or if the array is a member and you initialize it with member{{1, 2, 3, 4, 5}}, you cannot only pass one pair of braces.

This is because there were worries of possible overload ambiguities when braces are passed to functions, as in f({{1, 2, 3, 4, 5}}). But it caused some discussion and an issue report has been generated.

Essentially, the = { ... } initialization always has been able to omit braces, as in

int a[][2] = { 1, 2, 3, 4 };

That's not new. What is new is that you can omit the =, but then you must specify all braces

int a[][2]{ {1, 2}, {3, 4} };
于 2012-01-14T16:00:08.490 に答える