Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iinitializing a constexpr std::array of pairs

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

int main() {
}
like image 329
fouronnes Avatar asked Mar 11 '19 10:03

fouronnes


People also ask

Why array is internally treated as pointer?

Array- An array is contiguous piece of memory that holds space for number of items ( which are equal to size of array ) , Elements in the array should be of similar datatype. Memory to array is decided at compile time of program. The name of array is pointer which holds the base address of array. That's why Array is Internally Treated as Pointer.

Can I put constexpr in front of void init_Prime()?

From what I have read I should be able to put constexpr in front of void init_prime () in prime.cpp because it can be evaluated at compile time. If I do this the compiler tells me I have to put constexpr in front of bool is_prime (int i) as well. If I do this however, I can no longer call the function in main.

Why can’t std ::size (r) be a constant expression?

As already pointed out, since r is a reference, std ::size( r) cannot be a constant expression, so this constraint cannot be made to work. This would work fine if r was not a reference (but then we’d be constructing a span to refer to a range that is about to get destroyed, so this is a particularly tortured use of “work fine”).

What does const void printarray do in C++?

void printArray (const std::array<int, 5> &n) - const is used here to prevent the compiler from making a copy of the array and this enhances the performance. The passed array will be n in this function as &n is the parameter of the function 'printArray'.


1 Answers

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.

like image 167
StoryTeller - Unslander Monica Avatar answered Sep 28 '22 15:09

StoryTeller - Unslander Monica