这是我的密码。
如果我不评论// typedef auto getFoo1() -> decltype(*this);,这个程序可以在gcc身上运行,但是它在clang (https://godbolt.org/z/jzs3f6oM7)上编译失败。
class Foo {
public:
// not work on clang but work on gcc
// typedef auto getFoo1() -> decltype(*this);
auto getFoo2() -> decltype(*this);
};
int main() {
Foo f;
return 0;
}错误是
<Compilation failed>
# For more information see the output window
x86-64 clang 14.0.0 - 1232ms
Output of x86-64 clang 14.0.0 (Compiler #1)
<source>:6:41: error: invalid use of 'this' outside of a non-static member function
typedef auto getFoo1() -> decltype(*this);我想知道,getFoo1()和getFoo2()有什么区别?运行时,getFoo1()和getFoo2()是否存在于内存或其他位置?
发布于 2022-08-23 10:13:27
只有少数地方允许this出现,并且[expr.prim.this]列出了它们,即它可以出现在成员函数的声明、成员函数模板和非静态数据成员的默认初始化器中。
typedef声明一个类型别名,所以上面的任何一个都不允许this出现在typedef声明中。GCC接受它是错误的。
这个规则也是有道理的。this只在非静态成员函数定义中才有意义。它的价值和它的类型也取决于这一点。例如,this应该是const-qualified当且仅当非静态成员函数是const-qualified。
但是,表单的typedef
typedef auto getFoo1() -> decltype(*this);与成员函数无关。它只是为一个普通函数类型声明了一个类型别名,该类型可以用于声明任何函数,无论是否为成员函数,也可以用于任何类中。那么,在这种情况下,this应该拥有什么样的类型呢?Foo*、const Foo*等等?
如果您只需要引用类类型本身,直接使用Foo而不是遍历decltype(*this)。
https://stackoverflow.com/questions/73455453
复制相似问题