3

以下编译没有错误:

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'”,如下所示:A afunc

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

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

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

1 回答 1

3

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

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

于 2019-03-11T16:19:58.947 回答