fouronnes
fouronnes

Reputation: 4028

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"}};

Upvotes: 9

Views: 5386

Answers (2)

Dominik Grabiec
Dominik Grabiec

Reputation: 10655

An alternative in C++20 is to use std::to_array which allows you to create an array where you don't need to specify the size up front.

constexpr auto strings = std::to_array<std::pair<int, const char*>>({
{0, "Int"},
{1, "Float"},
{2, "Bool"},
});

Upvotes: 0

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.

Upvotes: 15

Related Questions