从成员变量访问静态 constexpr 成员,GCC 错误?
Accessing a static constexpr member from a member variable, GCC bug?
以下编译无误:
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 编译时,如果我们将变量 "use of 'this' in a constant expression" =12=] 在函数 func
中,像这样:
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
是封闭 class 的成员。但是常量表达式求值无法在非 constexpr
成员函数 ([expr.const]/2.1) 中访问 this
。即使为了获得静态成员 n
的值,评估 this
似乎是不必要的,标准要求评估 a
(这意味着 this->a
),即使它不需要值;参见 [expr.ref]/1 及其脚注。
如果 func
被标记为 constexpr
,GCC 将接受您的代码。正如评论中指出的那样,最好只写 A::n
。
以下编译无误:
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 编译时,如果我们将变量 "use of 'this' in a constant expression" =12=] 在函数 func
中,像这样:
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
是封闭 class 的成员。但是常量表达式求值无法在非 constexpr
成员函数 ([expr.const]/2.1) 中访问 this
。即使为了获得静态成员 n
的值,评估 this
似乎是不必要的,标准要求评估 a
(这意味着 this->a
),即使它不需要值;参见 [expr.ref]/1 及其脚注。
如果 func
被标记为 constexpr
,GCC 将接受您的代码。正如评论中指出的那样,最好只写 A::n
。