jeudi 26 septembre 2019

member function not found after static cast from base to derived

I am trying to build a function called 'step', which takes a base class pointer and does some things. Currently, I am using a dummy base class in order to enable a common interface.

#include <iostream>

using namespace std;

class gym_action //dummy base
{
public:
    virtual ~gym_action(){}
};

template<typename T>
class action_helper : public gym_action
{
    public :
        action_helper(T a) : action_item(a){}
        T get_action() {return action_item;}

    private:
       T action_item;

};

void step(gym_action* act)
{
    act = dynamic_cast<action_helper<int>*>(act);
    cout<<act->get_action()<<endl;
}

int main()
{

    action_helper<int> a(2);
//I will have more action_helper instansiations, like action_helper<Eigen::VectorXf> etc
    cout<<a.get_action()<<endl;
    step(&a);

}

This code fails with gym_class has no member function get_action. Clearly, the reason for this is that there is no virtual function get_action in the base class.

However, how can I define this? The reasons I can't currently is that each templatized get_action function returns a different type T. One possible way is I define every possible overload ahead of time in the base class, but this seems like a bad design Thoughts?

Aucun commentaire:

Enregistrer un commentaire