这个带有 `this` 尾随 return 类型的函数指针是否合法?
Is this function pointer with `this` in trailing return type legal?
class C {
auto (*foo)() -> decltype(this);
};
GCC、MSVC 和 clang 接受此代码,但 icc 不接受。
引用 n4140(大致为 C++14)[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). [...]
4 Otherwise, if a member-declarator declares a non-static data member (9.2) of a class X
, the expression this is a prvalue of type "pointer to X
" within the optional brace-or-equal-initializer. It shall not appear elsewhere in the member-declarator.
由于您没有声明成员函数或成员函数模板,因此 p3 不适用,但这将使代码在您实际声明成员函数的非指针情况下有效:尾随return 类型在可选的 cv-qualifier-seq 和声明符的末尾之间,在 const
成员函数的定义中更清楚:
auto foo() const -> decltype(this) { }
p4 在这里适用。它只允许 this
出现在初始化程序中。你把它放在别处。 p3 不适用,所以 ICC 拒绝这个是正确的。
class C {
auto (*foo)() -> decltype(this);
};
GCC、MSVC 和 clang 接受此代码,但 icc 不接受。
引用 n4140(大致为 C++14)[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). [...]4 Otherwise, if a member-declarator declares a non-static data member (9.2) of a class
X
, the expression this is a prvalue of type "pointer toX
" within the optional brace-or-equal-initializer. It shall not appear elsewhere in the member-declarator.
由于您没有声明成员函数或成员函数模板,因此 p3 不适用,但这将使代码在您实际声明成员函数的非指针情况下有效:尾随return 类型在可选的 cv-qualifier-seq 和声明符的末尾之间,在 const
成员函数的定义中更清楚:
auto foo() const -> decltype(this) { }
p4 在这里适用。它只允许 this
出现在初始化程序中。你把它放在别处。 p3 不适用,所以 ICC 拒绝这个是正确的。