gpt4 book ai didi

c++ - 在类内部,为什么 `auto b() -> decltype(a()) {}` 有效,但 `decltype(a()) b() {}` 无效?

转载 作者:IT老高 更新时间:2023-10-28 21:46:45 26 4
gpt4 key购买 nike

考虑以下代码:(Ideone)

struct S
{
int a() {return 0;}
decltype(a()) b() {return 1;}
};

它给了我以下错误:

error: cannot call member function 'int S::a()' without object


另一方面,这段代码编译得很好:(Ideone)

struct S
{
int a() {return 0;}
auto b() -> decltype(a()) {return 1;}
};


为什么一个例子有效,而另一个却编译失败?

两个示例中的编译器行为是否完全正确?

如果编译器是正确的,那么为什么标准会要求这种奇怪的行为?

最佳答案

由于a是一个非静态成员函数,a()被解释为(*this).a()。部分引自 [expr.prim.general]/3,

If a declaration declares a member function or member function template of a class X, the expression this is a prvalue of type “pointer to cv-qualifier-seq X” between the optional cv-qualifer-seq and the end of the function-definition, member-declarator, or declarator. It shall not appear before the optional cv-qualifier-seq and it shall not appear within the declaration of a static member function (although its type and value category are defined within a static member function as they are within a non-static member function).

trailing-return-type 出现在可选的 cv-qualifier-seq 之后(在您的示例中省略,因为 S::b不是 cv 限定的)所以 this 可以出现在那里,但它不能出现在之前。

关于c++ - 在类内部,为什么 `auto b() -> decltype(a()) {}` 有效,但 `decltype(a()) b() {}` 无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37038832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com