2017-02-19 124 views
3

我與static constexpr屬性有一些困難:它與積分類型一起使用,有enum class成員,但是當我嘗試使用靜態初始化的整數數組完成時,它失敗鏈接說undefined reference to S::a裏面mainC++ 14靜態constexpr成員數組鏈接失敗

這是與鏗3.9或g ++ 6.3和ld 2.27.90;和所有與-std=c++14

這裏是重現此最快的片段:

struct S 
{ 
    static constexpr int a[5] = {0}; 
}; 


int main() 
{ 
    S s{}; 
    [[gnu::unused]] int b = s.a[0]; // force S stuff to be emitted 
    return 0; 
} 

謝謝您可能有這種情況的任何建議。

+0

你需要定義你的對象;在命名空間範圍:'constexpr int S :: a [5];' – ildjarn

+0

@ildjarn謝謝!但是你知道爲什麼我必須爲數組做這個而不是像純整型類型的其他東西嗎? – suut

回答

5

考慮以下代碼:

enum class E { foo, bar }; 
struct S 
{ 
    static constexpr int a[5] = {0}; 
    static constexpr int b = 42; 
    static constexpr E e = foo; 
}; 

所有以上是聲明,並定義。對於每一個,你必須提供一個定義

int S::a[5]; 
int S::b; 
E S::e; 

它與整型,用枚舉類成員

此作品或多或少意外。具體而言,它的工作原理是因爲您從來沒有獲取該變量地址的上下文(從不使用ODR-使用該變量)。

通常我看到人們將一個無辜的前瞻性呼叫std::max,突然發現,他們並沒有提供一個定義。那就是:

int main() 
{ 
    printf("%d\n", S::b);  // works fine 
    int x = std::max(1, S::b); // fails to link in non-optimized build. 
}