2017-03-01 50 views
2

我嘗試定義類範圍之外的靜態變量,如:與模板類的靜態變量衝突的聲明

template<typename T> 
struct Foo { 
    void set(int i) { 
    } 
    static constexpr decltype(&Foo<T>::set) i = &Foo<T>::set; 
}; 

template<typename T> 
constexpr decltype(&Foo<T>::set) Foo<T>::i; 

Live example.

,但我得到以下錯誤(所有GCC> = 4.7):

conflicting declaration 'constexpr decltype (& Foo<T>::set(int)) Foo<T>::i' 
note: previous declaration as 'constexpr decltype (& Foo<T>::set(int)) Foo<T>::i' 

所有clang版本(clang> = 3.2)對我的代碼沒有任何問題。

這個問題似乎是函數的參考。它的工作原理沒有使用模板類。

我的問題:

  • 它是一個錯誤嗎?
  • 如何在gcc中做到這一點?

回答

1

我不知道這是否是一個錯誤或沒有,但你可以做這樣的:

template<typename T> 
struct Foo { 
    void set(int i) { 
    } 

    typedef decltype(&Foo<T>::set) function_type; 
    static constexpr function_type i = &Foo<T>::set; 
}; 

template<typename T> 
constexpr typename Foo<T>::function_type Foo<T>::i; 

int main() 
{ 
    Foo<int> f; 
}