如何启用/禁用在 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/