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() {
}
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.
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.
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”).
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'.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With