考虑以下代码:(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 expressionthis
is a prvalue of type “pointer to cv-qualifier-seqX
” 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/