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

标签 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 中你会怎么做呢?

最佳答案

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

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

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

关于d - 启用或禁用 const 数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27821818/

相关文章:

preprocessor - D 编程语言中 "#ifdef"、 "#ifndef"、 "#else"、 "#elif"、 "#define"、 "#undef"的类似物是什么?

string - 将 http 响应压缩为字符串的精确副本

node.js - NodeJS 在计算质数时比 D 更快。如何?

d - 在 D 中的关联数组中查找最大值元素

performance - D 的快速线性系统求解器?

d - 变量转储器模板函数不考虑范围

arrays - D - 是否有用于读取和写入字节的字节缓冲区?

reflection - 在 D 中透明地同步对象中的任意属性

java - D转换器: Is there a way to convert D language to java or C++?

templates - 难以理解 D 中的模板、模板混入、模板函数和作用域