2

In this code:

#include <array>
#include <cstdint>

struct K {
    std::array<char, 4> a;
    std::uint8_t b;
};

const K k1 = { {'T', 'e', 's', 't'}, 1 };

class X {
    const K k2 = { {'A', 'b', 'c', 'd'}, 2 };
};

I can initialize a global object k1 just fine. But trying to use the same syntax on a default initializer of the class member k2 gives compiler errors (similar errors from g++-4.8.2 and g++-5.2.0):

main.cpp:12:44: error: array must be initialized with a brace-enclosed initializer
     const K k2 = { {'A', 'b', 'c', 'd'}, 2 };
                                            ^
main.cpp:12:44: error: too many initializers for 'std::array<char, 4ul>'

What's the correct way to initialize k2 at its declaration?

aschepler
  • 70,891
  • 9
  • 107
  • 161
  • 1
    What compiler are you using? – Nicol Bolas Dec 21 '15 at 21:34
  • Clang accepts it with warning `main.cpp:9:17: warning: suggest braces around initialization of subobject [-Wmissing-braces]` (for `std::array` initialization). – Jarod42 Dec 21 '15 at 21:38
  • [When can outer braces be omitted in an initializer list?](http://stackoverflow.com/questions/11734861/when-can-outer-braces-be-omitted-in-an-initializer-list) – M.M Dec 21 '15 at 21:58

1 Answers1

2

You just need an extra pair of braces:

class X {
    const K k2 = { {{'A', 'b', 'c', 'd'}}, 2 };
};
101010
  • 41,839
  • 11
  • 94
  • 168