Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid boilerplate on template arguments when calling parent constructor

So let's say I have a class with a lot of template arguments, one of them is the derived class to use CRTP:

template <typename Derived, typename A, typename B, typename C, typename D>
class BaseFoo  {
public:
    BaseFoo(A& a) {}
};

And I want to inherit it:

class DerivedFoo : public BaseFoo<DerivedFoo, Bc, Cc, Dc, Ec> {
public:
    DerivedFoo(A& a) : BaseFoo<DerivedFoo, Bc, Cc, Dc, Ec>(a) {}
};

Is there any trick to avoid all the explicit template argument mentioning?

It is ok if I still have to state Derived as template arguments.

like image 553
alesegdia Avatar asked Dec 20 '22 00:12

alesegdia


1 Answers

Just use the derived class' name and lookup the base class name in it if the base class is dependent. If it is not dependent, you can just name the base class unqualified, since it is in scope. No need for all the template arguments

class DerivedFoo : public BaseFoo<DerivedFoo, Bc, Cc, Dc, Ec> {
public:
    DerivedFoo(A& a) : BaseFoo(a) {}
};

Every class declares its name inside itself. Not only normal classes, but also class template instances. So BaseFoo refers to BaseFoo<...> in its own scope and the scope of its derived classes.

like image 164
Johannes Schaub - litb Avatar answered Dec 22 '22 10:12

Johannes Schaub - litb