c++ - 静态变量与模板类的冲突声明

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

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

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 中实现?

最佳答案

不知道是不是bug,但是你可以这样操作:

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;
}

关于c++ - 静态变量与模板类的冲突声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42534051/

相关文章:

C++ 使用来自 const 函数的映射调用指向成员的指针

c++ - 在 GLSL 中重新使用内置 OpenGL 变量定义自己的制服。为什么?

c++ - 使用帧指针优化进行调试

c++ - 对静态 constexpr 的 undefined reference

javascript - 使用下划线模板构建数独板

c++ - 连接 2 个 char* 会产生奇怪的结果

c++ - 如何避免将参数传递给基于引用的帮助程序类的模板实例化

c++ - 这个线程池/多核模拟有什么问题

c++ - 类模板的公共(public)继承意外失败

php - CodeIgniter Performance 多次加载 View 与 View 循环