2015-01-07 29 views
5

如何启用/禁用在常量数组中包含元素?在常量数组中启用或禁用元素

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?

回答

3

有几种方法。一种方法是有条件地附加的阵列,使用三元运算符:

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

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

+0

typo:include_germary。除非germary是lang,否则无效。的germar。 Germar,这个重要的国家^^ –

+0

固定:) 此外,我应该提到'include_germany'预计是一个常数,而不是一个版本,所以它应该使用'const' /'enum'声明。请参阅下面的@BBaz'答案,以使其与'-version'配合使用。 –

+0

不幸的是,这不会编译... – user1461607

1

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

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

构建阵列的过程与Cyber​​Shadow答案中所述的完全相同。

+0

我认为你需要'const'或'enum',而不是'static'。 –