Making strange polymorphism
I'm trying to make some kind of strange polymorphism on C++:
I have two trees of classes:
State <-- Stage <-- Stage_1, Stage_2, Stage_3
Action <-- ActionState <-- ActionState_Clear, ActionState_Begin, ActionState_[...]
I want to define some methods on Stage_1 that get an Action as parameter:
State
{
virtual void exec_action(Action *tAct)
{
std:cout << "NOT IMPLEMENTED" << endl;
};
}
Stage_1
{
virtual void exec_action(ActionStag开发者_开发百科e_Clear *tAct)
{
std::cout << "ACTION STAGE CLEAR" << endl;
}
virtual void exec_action(ActionStage_Begin *tAct)
{
std::cout << "ACTION STAGE BEGIN" << endl;
}
}
Action *pAct = new ActionStage_Clear();
State* pSta = new Stage_1();
**pSta->exec_action(pAct);**
I'd like it to show 'ACTION STAGE CLEAR', but it shows 'NOT IMPLEMENTED'. That's - I think - because there isn't any implementation of exec_action(Action *) (although there are some for its son-classes).
EDIT: I'll show you a little part of the diagram: I have Stage(s) and Action(s). I'll have a ptr to Stage_1, 2 .. and a ptr to Action_1, 2 ... I want to call Stage_n->exec_action(Action_n) and that should execute the code of the son: Action_1::exec_action(Action_1). (if it's not implemented it should call Action::exec_action(Action)).
How can I fix it? Is there any other way to make it work?
Thanks, forgive my English.
You want double dispatch here. Virtual functions directly provide only single one. One good example of double dispatch is in Visitor pattern, which could be directly applicable to your task.
You can only override in your base classes contravariantly: the type of the argument in the derived class method must be less derived than the one in the base class.
Otherwise (as in your case), you are just writing a different function.
精彩评论