Search code examples
d

Enable or disable elements in const array


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?


Solution

  • 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).