c++ - 这个尾随返回类型为 `this` 的函数指针是否合法?

标签 c++ c++11 language-lawyer function-pointers

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 不适用,但这将使代码对于您实际声明成员函数的非指针情况有效:尾随返回类型在可选的 cv-qualifier-seq 和声明符的末尾之间,在 const 成员函数的定义中更清楚:

auto foo() const -> decltype(this) { }

p4 在这里适用。它只允许 this 出现在初始化程序中。你把它放在别处。 p3 不适用,因此 ICC 拒绝这一点是正确的。

关于c++ - 这个尾随返回类型为 `this` 的函数指针是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47165384/

相关文章:

java - 为什么在 Java 中初始化数组对象时不需要提供括号?

c - sscanf 是否需要以空字符结尾的字符串作为输入?

c++:仅cin整数

c++ - "istreambuf_iterator"后读取文件失败

c++ - 为什么我的模板需要 C++ 链接?

c++ - 将多个二维数组存储在一个变量中

c++ - 仅当指针作为参数传递给函数时才存在类型别名问题吗?

c++ - 将 unique_ptr<Derived>& 传递给接受 unique_ptr<Base>& 的函数

c++ - 无法正确调用 `connect`

c++ - 如何确定存储在数组中的项目数?