8

I've read the similar questions, but does anyone know why if I have a struct

struct ArabicRoman {
    char roman;
    int arabic;
};

I can initialise a C++ std::array in the following way:

ArabicRoman M({'M', 1000});
ArabicRoman D({'D', 500});
array<ArabicRoman, 2> const SYMBOLS({ M, D });

I can initialise a C-style array in the following way:

ArabicRoman const SYMBOLS[]({ {'M', 1000}, {'D', 500} });

However, the following is not compiling:

array<ArabicRoman, 2> const SYMBOLS({ {'M', 1000}, {'D', 500} });

any workaround to initialise C++ style arrays of structs?

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
stivlo
  • 83,644
  • 31
  • 142
  • 199

1 Answers1

13

You need to replaces parentheses with braces:

std::array<ArabicRoman, 2> const SYMBOLS {{ {'M', 1000}, {'D', 500} }};
                                         ^                           ^

LIVE DEMO

101010
  • 41,839
  • 11
  • 94
  • 168
  • thanks! I saw now in the reference http://en.cppreference.com/w/cpp/container/array that this style of double brace initialisation is C++11 syntax, and won't be required any more in C++14 – stivlo Nov 07 '15 at 18:45
  • @stilvo It is true that you don't need double braces in simple cases, but with nested braces they can be hard to avoid... – Marc Glisse Nov 07 '15 at 18:51