繁体   English   中英

从成员变量GCC bug访问静态constexpr成员?

[英]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编译时 ,如果我们在函数func变量A a的成员变量,我们会得到错误“在常量表达式中使用'this' ,如下所示:

template<int j> struct B {
    A a;
    void func() {
        TemplateClass<j, a.n> c;
    }
};

使用MSVC进行编译不会出错。 比较两个编译器

  • 我不明白为什么会出错。 这是一个错误吗?
  • 是否有解决此错误的解决方法?

GCC是正确的。 模板参数必须是常量表达式,和an隐含意味着this->an ,因为a是封闭类的成员。 但常量表达式评估不能访问this一内部非constexpr成员函数([expr.const] /2.1)。 并且即使为了获得静态成员n的值而this评估似乎是不必要的,但是该标准要求即使不需要其值,也要评估a (这意味着 - this->a ); 见[expr.ref] / 1及其脚注。

如果func标记为constexpr GCC将接受您的代码。 正如评论中指出的那样,最好只编写A::n

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM