gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:22:16 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com