我可以在C ++中实现一个自主的“self”成员类型吗?

我可以在C ++中实现一个自主的“self”成员类型吗?

问题描述:

C ++ 缺少等同于 PHP self 关键字,其计算为封闭类的类型。

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;
};

但我必须再次写 Foo

我可以使用 decltype 的一些组合,和朋友,使这项工作自主? 我已尝试下列,但在那个地方无效:

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

这里是如何你可以不重复Foo的类型来做:

Here's how you can do it without repeating the type of Foo:

template <typename...Ts>
class Self;

template <typename X, typename...Ts>
class Self<X,Ts...> : public Ts...
{
protected:
    typedef X self;
};

#define WITH_SELF(X) X : public Self<X>
#define WITH_SELF_DERIVED(X,...) X : public Self<X,__VA_ARGS__>

class WITH_SELF(Foo)
{
    void test()
    {
        self foo;
    }
};

如果要从 Foo 您应该使用以下方式使用宏 WITH_SELF_DERIVED

If you want to derive from Foo then you should use the macro WITH_SELF_DERIVED in the following way:

class WITH_SELF_DERIVED(Bar,Foo)
{
    /* ... */
};

你甚至可以使用尽可能多的基类来进行多重继承(感谢可变参数模板和可变参数宏):

You can even do multiple inheritance with as many base classes as you want (thanks to variadic templates and variadic macros):

class WITH_SELF(Foo2)
{
    /* ... */
};

class WITH_SELF_DERIVED(Bar2,Foo,Foo2)
{
    /* ... */
};

我已经验证了这个工作在gcc 4.8和clang 3.4。

I have verified this to work on gcc 4.8 and clang 3.4.