Using CRTP with an interface

I have a set of classes that implement the same business methods. I plan to use CRTP instead of virtual sending due to performance reasons. But I would like to keep the coding convenience in one interface, which comes with inheritance and virtual methods.

Is it good that my specialized classes inherit both from a template abstract class that uses CRTP to store common code and inherits from a pure virtual class, so I can create instances of each type, but it depends on my client code only on the interface? Even better, how can I use CRTP to provide a single interface for client code when there are multiple implementations?

+5
source share
1 answer

Sure. You can use a similar approach, which is quite true:

class Interface { public: virtual void doSomething() = 0; //... }; template<typename T> class GeneralImpl : public Interface { public: void doSomething() override { auto someDetail = T::somethingStatic(); //... static_cast<T*>(this)->someMember(); //... } } class SpecificImpl : public GeneralImpl<SpecificImpl> { public: static int somethingStatic() { //... } void someMember() { //... } }; int main() { std::vector<Interface*> vec; SpecificImpl instance; //... vec.push_back(&instance); //... for(auto* inst : vec) { inst->doSomething(); } //... } 
+5
source

Source: https://habr.com/ru/post/1260642/


All Articles