C++ lacks the equivalent of PHP's self
keyword, which evaluates to the type of the enclosing class.
It's easy enough to fake it on a per-class basis:
struct Foo
{
typedef Foo self;
};
but I had to write Foo
again. Maybe I'll get this wrong one day and cause a silent bug.
Can I use some combination of decltype
and friends to make this work "autonomously"? I tried the following already but this
is not valid in that place:
struct Foo
{
typedef decltype(*this) self;
};
// main.cpp:3:22: error: invalid use of 'this' at top level
// typedef decltype(*this) self;
(I'm not going to worry about the equivalent of static
, which does the same but with late binding.)
Unless the type needs to be member type of the enclosing class you could replace the use of
self
withdecltype(*this)
. If you use it in many places in your code you can define a macroSELF
as follows: