c++ - 从成员变量访问静态 constexpr 成员,GCC 错误?

标签 c++ templates compiler-errors compiler-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 编译,如果我们为变量 创建一个成员变量,我们会得到错误“在常量表达式中使用‘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/

相关文章:

templates - 带有 url 参数的flask render_template

java - 事件处理程序有编译错误 : "local variables referenced from a lambda expression must be final"

c++ - HashMap 错误: no match for call to ‘(const __gnu_cxx::

c++ - 为什么在 C++ 顶点函数中有两个括号 [?

c++ - 垂直翻转图像

c++ - 模板尾部结构凸起 "incomplete type in nested name specifier"

java - Intellij Idea 评论错误

c++ - 跨平台 C++ : Use the native string encoding or standardise across platforms?

c++ - 从头文件中的命名空间访问类型

c++ - 将比较器传递给声明为类成员的 priority_queue