13

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?

1
  • 4
    You need more braces. Commented Nov 7, 2015 at 18:36

1 Answer 1

19

You need to replaces parentheses with braces:

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

LIVE DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

thanks! I saw now in the reference 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
@stilvo It is true that you don't need double braces in simple cases, but with nested braces they can be hard to avoid...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.