我尝试在类范围之外定义一个静态变量,例如:
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;
但我得到以下错误(对于所有 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/