在类中,为什么`auto b() - > decltype(a()){}`工作,但`decltype(a())b(){}`不? [英] Inside of a class, why `auto b() -> decltype(a()) {}` works, but `decltype(a()) b() {}` does not?

查看:115
本文介绍了在类中,为什么`auto b() - > decltype(a()){}`工作,但`decltype(a())b(){}`不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:(Ideone)

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

它给我以下错误:


错误:无法调用成员函数'int S :: a()'无对象

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


另一方面,此代码编译正常:(Ideone)

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



为什么一个示例工作,但另一个无法编译?


Why one example works, but another fails to compile?

编译器的行为是否完全正确?

Is compiler behavior fully correct in both examples?

如果编译器是正确的,

If compiler is correct, then why the standard mandates such strange behavior?

推荐答案

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

Since a is a non-static member function, a() is interpreted as (*this).a(). Quoting in part from [expr.prim.general]/3,


如果声明声明了类的成员函数或成员函数模板 X ,表达式 this
是类型的指针指向 cv-qualifier-可选的 cv-qualifer-seq
函数定义的结尾之间的 成员声明器声明器。它不会出现在可选的 cv-qualifier-seq
之前,它不会出现在静态成员函数的声明中(尽管其类型和值
类别在非静态成员函数中的静态成员函数)。

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).

em>在可选的 cv-qualifier-seq 之后(在您的示例中省略,因为 S :: b 不是cv限定的) code>这个可以出现在那里,但不能出现。

The trailing-return-type comes after the optional cv-qualifier-seq (omitted in your examples, since S::b is not cv-qualified) so this can appear there, but it cannot appear before.

这篇关于在类中,为什么`auto b() - > decltype(a()){}`工作,但`decltype(a())b(){}`不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆