启用或禁用const数组中的元素

use*_*607 5 d

如何启用/禁用const数组中的元素包含?

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}
];
Run Code Online (Sandbox Code Playgroud)

在C中,您可以使用#ifdef来启用或禁用数组中的特定元素,但是如何在D中执行此操作?

Vla*_*eev 3

有几种方法。一种方法是使用三元运算符有条件地追加数组:

static const country[] countries = [
  country("Iceland", 800),
  country("Australia", 309),
] ~ (include_germany ? [country("Germany", 233254)] : []) ~ [
  country("USA", 3203)
];
Run Code Online (Sandbox Code Playgroud)

您还可以编写一个计算并返回数组的函数,然后const用它初始化一个值。该函数将在编译时 (CTFE) 进行评估。