Reputation: 580
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. Any thoughts?
Upvotes: 0
Views: 50
Reputation: 206577
Even after the dynamic_cast
, the variable act
is still of type gym_action*
. Hence, you may not call a derived class member function on it.
Use a new variable.
auto temp = dynamic_cast<action_helper<int>*>(act);
if ( temp != nullptr )
{
cout << temp->get_action() << endl;
}
Upvotes: 1