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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…