Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
851 views
in Technique[技术] by (71.8m points)

c++11 - Can I implement an autonomous `self` member type in C++?

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A possible workaround (as you still have to write the type once):

template<typename T>
struct Self
{
protected:
    typedef T self;
};

struct Foo : public Self<Foo>
{
    void test()
    {
        self obj;
    }
};

For a more safer version we could assure that T actually derives from Self<T>:

Self()
{
    static_assert(std::is_base_of<Self<T>, T>::value, "Wrong type passed to Self");
}

Notice that a static_assert inside a member function is probably the only way to check, as types passed tostd::is_base_of have to be complete.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...