【问题标题】:Conflicting declaration for static variable with template class静态变量的声明与模板类冲突
【发布时间】:2017-07-20 22:01:08
【问题描述】:

我尝试在类范围之外定义一个静态变量,例如:

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 中怎么做?

【问题讨论】:

    标签: c++ c++11 templates gcc clang


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多