2015-01-07 26 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'。 –