How does one enable/disable the inclusion of elements in an const array?
struct country {
const string name;
ulong pop;
};
static const country countries[] = [
{"Iceland", 800},
{"Australia", 309},
//... and so on
//#ifdef INCLUDE_GERMANY
version(include_germany){
{"Germany", 233254},
}
//#endif
{"USA", 3203}
];
In C, you can use #ifdef to enable or disable a particular element in an array, but how would you do that in D?
There are several ways. One way is to append an array conditionally, using the ternary operator:
static const country[] countries = [
country("Iceland", 800),
country("Australia", 309),
] ~ (include_germany ? [country("Germany", 233254)] : []) ~ [
country("USA", 3203)
];
You can also write a function which computes and returns the array, then initialize a const
value with it. The function will be evaluated at compile-time (CTFE).
You can compile with the custom switch-version=include_germany
. In the code you define a static bool:
static bool include_germany;
version(include_germany){include_germany = true;}
To build the array is then identical as described in the CyberShadow answer.
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