2

I was trying to create a std::array of char array so that I could declare it static constexpr.

eg:

#include <array>

int main(){

  static constexpr char A[] = "abc";
  static constexpr char B[] = "def";
  static constexpr std::array<char[], 3> tmp{A, B};
}

When I do this I get error message " too many initializers for"

mato
  • 503
  • 8
  • 18

3 Answers3

1

By output of your compiler I could surmise that you have a non-standard extension active. Stricly ISO-wise use of char[] as parameter of template is not legal,. Some compilers would treat that as char[0].

what your array meant to store? way you're trying to do it would store adresses of array to char (and only way to do so would be replace char[] by by const char* in template parameters. std::array is trivial class which stores data statically so you cannot implement array with variable length of strings that way.

Either 1) abolish constexpr and use std::string 2) use const char* 3) worst case (which sometimes is the best) - use fixed array length or "naked" 2-dimensional array with aggregate initializer list.

Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42
  • When I said it to store char[] why is std::array trying to store address? shouldn't it store char[]? – mato Feb 09 '18 at 15:18
  • @mike depends on which compiler you use. judging by output of yours it was treating char[] as char[0] and is unable to store literals you give it. One I used was saying that char[] is illegal, and it is by ISO standard. so 1) store addresses 2) store string classes 3) store arrays of fixed length. actually can use std::array instead of char[x] – Swift - Friday Pie Feb 09 '18 at 15:21
0

You may use:

static constexpr std::array<char[4], 2> tmp {{{ A[0], A[1], A[2], A[3] },
                                              { B[0], B[1], B[2], B[3] }}};

or

static constexpr std::array<char[4], 2> tmp { "abc", "def" };

From http://en.cppreference.com/w/cpp/container/array:

When initializing an object of array type, the initializer must be either a string literal (optionally enclosed in braces) or be a brace-enclosed list of initialized for array members.

Thus you cannot initialize an array (member of std::array of char[4]) by an object of another array.

Daniel Langr
  • 22,196
  • 3
  • 50
  • 93
0

With C++20 std::to_array can be used.

static constexpr char A[] = "abc";
static constexpr char B[] = "def";
static constexpr auto tmp = std::to_array({A, B});
pjb
  • 61
  • 4