Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable or disable elements in const array

Tags:

d

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?

like image 686
user1461607 Avatar asked Sep 29 '22 01:09

user1461607


2 Answers

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

like image 87
Vladimir Panteleev Avatar answered Oct 06 '22 09:10

Vladimir Panteleev


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.

like image 29
Abstract type Avatar answered Oct 06 '22 10:10

Abstract type