以下编译没有错误:
template<int j, int i>
struct TemplateClass {
int arr[i];
};
struct A {
inline static constexpr int n = 123;
};
template<int j> struct B {
void func() {
A a;
TemplateClass<j, a.n> c;
}
};
int main() {
B<456> b;
b.func();
}
但是,用 GCC 编译,如果我们为变量 创建一个成员变量,我们会得到错误“在常量表达式中使用‘this’”函数
,像这样:func
中的a
template<int j> struct B {
A a;
void func() {
TemplateClass<j, a.n> c;
}
};
用 MSVC 编译 没有错误。 Compare the two compilers,
- 我不明白为什么会出现错误。这是错误吗?
- 是否有解决此错误的方法?
最佳答案
海湾合作委员会是正确的。模板参数必须是常量表达式,并且 a.n
隐式表示 this->a.n
因为 a
是封闭类的成员。但是常量表达式求值无法访问非 constexpr
成员函数 ([expr.const]/2.1) 内的 this
。即使为了获得静态成员 n
的值而评估 this
似乎是不必要的,标准要求 a
(这意味着 this->a
) 即使不需要它的值也被计算;参见 [expr.ref]/1 及其脚注。
如果 func
被标记为 constexpr
,GCC 将接受您的代码。正如评论中指出的那样,最好只编写 A::n
。
关于c++ - 从成员变量访问静态 constexpr 成员,GCC 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55105937/