Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling derived class function from base class with templates without virtual

Tags:

c++

templates

I need to generate some members/methods of a class with a script. I'm trying to break up this class in two, with base class being generated members, and derived class having hand coded members. However, I'm getting stuck in figuring out how to call derived member function D::f2() from the base class B::f1().

Here is the simplified code:

#include <cstdio>

template <typename _T>
class B { 
public:
    void f3() {
        puts("okay");
    }
    void f1() {   
        f2();   // What C++ Magic to call f2() properly !!!
    }
};

class D : public B<D> {
public:
    void f2() {
        f3();
    }

};

int main() {
    D d;
    d.f1();
}

Is there any way, I can call D::f2() from B::f1() without using virtual functions ?

Added later:

If we do pointer manipulation, we will end up with injection, and I understand it's not a good idea, and I'll take the advice of not doing it. Let's stop that thread.

I am trying to find a solution using template only. I can generate any complex thing for the generated code. It can even be a several functors etc. However the hand coded written part should be hand-codable.

like image 800
vrdhn Avatar asked Feb 15 '23 08:02

vrdhn


1 Answers

If you really really really want to do it:

static_cast<_T*>(this)->f2();

As people have mentioned, this is the curiously recuring template pattern!

like image 157
Sean Avatar answered Apr 08 '23 12:04

Sean