Can I implement an autonomous `self` member type i

2019-01-01 07:02发布

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.)

标签: c++ c++11
13条回答
步步皆殇っ
2楼-- · 2019-01-01 07:47

Unless the type needs to be member type of the enclosing class you could replace the use of self with decltype(*this). If you use it in many places in your code you can define a macro SELF as follows:

#define SELF decltype(*this)
查看更多
登录 后发表回答