【问题标题】:Accessing a static constexpr member from a member variable, GCC bug?从成员变量访问静态 constexpr 成员,GCC 错误?
【发布时间】:2019-08-02 00:11:27
【问题描述】:

下面的编译没有错误:

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 编译,如果我们将变量 A a在函数func中,像这样:

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

使用 MSVC 编译不会出错。 Compare the two compilers,

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

【问题讨论】:

  • IIRC 这是上周被问到的。我会试着找到它。我相信这是缺陷报告的主题。
  • 是只使用A::n的解决方法吗?
  • @FantasticMrFox,是的,这行得通! decltype(a)::n 也可以。

标签: c++ templates compiler-errors compiler-bug


【解决方案1】:

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

如果func 被标记为constexpr,GCC 将接受您的代码。正如 cmets 中所指出的,最好只写 A::n

【讨论】:

  • 所以它不符合 MSVC ... 不是我所期望的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
  • 2022-01-03
  • 2018-08-06
  • 1970-01-01
相关资源
最近更新 更多