c++arraysc++14constexprstdarray

How do I initialize a constexpr std::array of std::pair<int, const char[]>?


In C++14, how do I initialize a global constexpr std::array of std::pair containing text strings? The following doesn't work:

#include <array>
    
constexpr std::array<std::pair<int, const char[]>, 3> strings = {
  {0, "Int"},
  {1, "Float"},
  {2, "Bool"}};

Solution

  • You are almost there. First of all, the char const[] type needs to be a pointer instead, because it is an incomplete type, that may not be held in a std::pair. And secondly, you are missing a pair of braces. The correct declaration will look like this:

    constexpr std::array<std::pair<int, const char*>, 3> strings = {{
      {0, "Int"},
      {1, "Float"},
      {2, "Bool"},
    }};
    

    The extra braces are required because std::array is an aggregate holding a raw C array, and so we need the braces mentioned explicitly so that {0, "Int"} is not taken erroneously as the initializer for the inner array object.