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

标签 c++ language-lawyer

考虑以下代码:(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/

相关文章:

c++ - 我有一个服务器在套接字上监听,有什么好方法可以通过多个线程来服务 CPU 绑定(bind)请求?

c++ - 如何从十六进制设置字符串值?

c++ - 为什么从 const 方法返回的 string& 无法编译?

c++ - 在 C++ 中使用函数式强制转换初始化变量

calloc() 总共可以分配超过 SIZE_MAX 吗?

c++ - 如何抛出文件和行号错误?

c - int a=1, b=a++;调用未定义的行为?

c++ - static_cast 的特殊规则

c++ - 什么表达式创建 xvalues?

c++ - 运算符 > 重载不起作用