Enabling or disabling elements in the const array

How to enable or disable the inclusion of elements in a 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 specific element in an array, but how would you do it in D?

+5
source share
2 answers

There are several ways. One way is to add the 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 that calculates and returns an array, and then initializes the const value with it. The function will be evaluated at compile time (CTFE).

+3
source

You can compile using the -version=include_germany custom switch. In the code, you define a static bool:

 static bool include_germany; version(include_germany){include_germany = true;} 

To build an array, it will be identical, as described in CyberShadow's answer.

+1
source

Source: https://habr.com/ru/post/1210564/


All Articles