Kilian
Kilian

Reputation: 543

C++ pass *this to base constructor

Is it valid, to pass *this to a base class constructor?

template<class Lambda>
struct EmptyL : Lambda
{
    EmptyL() : Lambda(*this) //<- is this valid c++?
    { }
};

int main () {    
auto l = []() { return 34; };
auto a = EmptyL<decltype(l)>();
return a();
}

EDIT1:

Upvotes: 1

Views: 336

Answers (1)

lorro
lorro

Reputation: 10880

This is valid AND is perfectly useful: your base class might have a template ctor which will then know the descendant's type.

struct Lambda {
    template<typename Desc>
    Lambda(const Desc&)
        : myType(Desc::myType)  // static in Desc
        , arity(Desc::arity) {} // static in Desc
    Type myType;
    const size_t arity;
};

At this point, we have runtime type enum w/o virtual table, we can extract arbitrary number of type-dependant params to members and you don't need to change all ctor calls in all descendants if you add one more (which is especially painful for virtual base classes otherwise), or worse yet, have virtual fns cor these. You just pass this everywhere - it's even macro-friendly :).

Yes, you can circumvent it by passing something else than this. No, it's not a safety function - it's a convenience function. This is very similar to CRTP, but the base is not a template as it doesn't need compile-time descendant type in the entire class, only inside the (template) ctor.

Upvotes: 2

Related Questions