10

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

2 Answers 2

16

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.

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

3 Comments

Why the relaxed aggregate initialization in C++14 doesn't work here? std::array<std::string,2> s = {"Hi","Hello"}; and std::array<std::string,2> s = {{"Hi, "Hello"}}; are both deemed identical after C++14 (in case of non-constexpr array). Why doesn't the same rule apply here ?
@aep - The brace elision algorithm has issues knowing that you mean to initialize the first pair and not the inner array.
I think with a bit of experiment I now understand the difference. Was mucking a bit around with a few combinations like std::array<std::string, 2> s={"hi", "hello"};, std::array<std::string, 2> s={{"hi", "hello"}};, std::array<std::string, 2> s={{"hi"}, {"hello"}};, std::array<std::string, 2> s={{{"hi"}, {"hello"}}}; to see the difference. Thanks for the explanation.
0

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

1 Comment

std::to_array is of questionable benefit here. If you're making your answer specific to C++20, you should probably also use std::string_view instead of const char*. Having the size information can be a big performance boost in some cases.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.