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

时间:2015-01-07 14:37:46

标签: 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}
];

在C中,您可以使用#ifdef启用或禁用数组中的特定元素, 但是你会怎么做到D?

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:1)

您可以使用自定义开关-version=include_germany进行编译。在代码中,您定义了一个静态bool:

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

然后构建阵列与Cyber​​Shadow答案中描述的相同。