C++ 缺乏的等效PHP的self
关键字,其评估的封闭类的类型.
在每个类的基础上伪造它很容易:
struct Foo
{
typedef Foo self;
};
Run Code Online (Sandbox Code Playgroud)
但我不得不再写Foo
一遍.也许有一天我会弄错,导致一个无声的错误.
我可以使用一些decltype
朋友和朋友的组合来"自主地"完成这项工作吗?我已尝试过以下内容但this
在该地方无效:
struct Foo
{
typedef decltype(*this) self;
};
// main.cpp:3:22: error: invalid use of 'this' at top level
// typedef decltype(*this) self;
Run Code Online (Sandbox Code Playgroud)
(我不会担心相同的static
,相同但后期绑定.)
为什么this
在静态成员函数中不允许未评估的上下文?
struct A
{
void f() {}
static void callback(void * self) // passed to C function
{
static_cast< decltype(this) >(self)->f();
}
};
Run Code Online (Sandbox Code Playgroud)
此代码给出错误:
错误:'this'不适用于静态成员函数
Run Code Online (Sandbox Code Playgroud)static_cast< decltype(this) >(self)->f(); ^~~~
decltype(this)
为了简洁需要(有时它会短得多VeryVeryLongClassName *
),另一个优点是意图更清晰.
标准说什么this
在静态成员函数中使用未评估的上下文?