Reputation: 543
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:
Lambda
are, that it has to be empty => static_assert(std::is_empty_v<Lambda>)
Upvotes: 1
Views: 336
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