I have some C that I need to convert to C++.
It does something like this:
enum
{
ELEM0,
ELEM1,
ELEM2,
ELEM3,
ELEM4,
MAX_ELEMS
}
#define LEN 16
static const char lut[MAX_ELEMS][LEN] =
{
[ELEM2] = "Two",
[ELEM3] = "Three",
[ELEM1] = "One",
[ELEM4] = "Four",
[ELEM0] = "Zero"
}
In practice I have hundreds of elements without any order in the array. I need to guarantee that the entry in the array ties up the enumeration to the appropriate text.
Is it possible to initialise an array using positional parameters like this in -std=gnu++11?
You can't. The const keyword is used to create a read only variable. Once initialised, the value of the variable cannot be changed but can be used just like any other variable. That means, a const qualified variable must not be assigned to in any way during the run of a program.
A static data member can be of any type except for void or void qualified with const or volatile. You cannot declare a static data member as mutable.
There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.
No. Per gcc documentation, Designated Initializers do not exists in GNU C++.
In ISO C99 you can give the elements in any order, specifying the array indices or structure field names they apply to, and GNU C allows this as an extension in C89 mode as well. This extension is not implemented in GNU C++.
Doesn't this solve you problem (although it's run-time):
static const std::map<int, std::string> lut =
{
std::make_pair(ELEM2, "Two"),
std::make_pair(ELEM3, "Three"),
std::make_pair(ELEM1, "One"),
};
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