multi level crtp how to pass a middle level type to an upper level

80 views Asked by At
// top level
template <typename Derived>
class A 
{
};

// approach 1 
template <typename Derived>
class B : public A <B<Derived>> 
{
};

// approach 2
template <typename Derived>
class B : public A <Derived> 
{
};


// lowest level
class C : public B <C> 
{
};

which one of the two approaches for the middle level nodes is correct when applying CRTP? (if there is no "better", which is commonly used/ has more advantages?).

1

There are 1 answers

2
Guillaume Racicot On BEST ANSWER

There is no really a best answer for that. You must use what's fit the best for you. I have some code where I used solution 1, and other coffee that uses solution 2. Use what fits your case the best.

The less you have to send the better it is, because the simpler your types will be. Coupling can easily become out of control with CRTP.

The solution 1 is the most generic one, as it won't force struct B to be a middle level, and could become the most derived without changing the base class.

The solution 2 in the other hand is the simplest one. If class A is part of a public API, it can be a considerable option.

There is also a third solution that came out quite handy for me worth mentioning:

template<typename Level1, typename Level2>
struct A {};

template<typename Derived>
struct B : A<Derived, B<Derived>> {};

You can use both now, but it add complexity to the code, and lot of coupling.