Is it correct to use the CRTP along with abstract class inheritance?

Viewed 118

Is it correct to use the CRTP (Curiously Recurring Template Pattern) along with the inheritance of an abstract class in C++? If so, is there any potential issue related to this construct? Below given code snippet describes my question.

template<class T>
class Base {
 void method_01() {
  static_cast<T*>(this)->method_01();
 }
};

class AbstractBase {
 virtual void method_02() = 0;
};

class A : public Base<A>, public AbstractBase {

};

Is there any possibility how replace the abstract class inheritance also by the CRTP so the A class uses the CRTP in double manner something like that

class A : public Base_01<A>, public Base_02<A> {

};
1 Answers

Where terms are concerned, a problem having an abstract class base is perpendicular to CRTP, because CRTP describes inheritance with static polymorphism, while AbstractBaseprovides dynamic polymorphism.

Dynamic polymorphism can be replaced by static if there is no type erasure required. CRTP emulates the virtual function call system at compile time without the costs in size or function call overhead, without possible UB or weird code malfunctions caused by UB (damaged vtable due to memory operations) at the disadvantage of not being able to make this choice at runtime. Classes produced by CRTP may have a standard memory layout.

There is no problem here provided the concrete classes will stay well-formed. It is possible that class AbstractBase can be used for type erasure and as a public interface, while class Base and class A would be a unit-local implementation of some component functionality.

Related