As an example to my question, imagine a base class like so:
struct Agent {
void compete(const Agent& competitor) const = 0;
};
Associated with a derived like this:
struct RockAgent;
struct PaperAgent;
struct ScissorsAgent: public Agent {
void compete(const Agent& competitor) const override {
if(dynamic_cast<const RockAgent*>(&competitor))
std::cout << "I have lost" << std::endl;
else if(dynamic_cast<const PaperAgent*>(&competitor))
std::cout << "I have won!" << std::endl;
//etc....
}
};
And compare it to this base:
struct PaperAgent;
struct RockAgent;
struct ScissorsAgent;
struct Agent {
void compete(const PaperAgent& competitor) const = 0;
void compete(const RockAgent& competitor) const = 0;
void compete(const ScissorsAgent& competitor) const = 0;
};
and this derived:
//forward needed classes.....
struct PaperAgent: public Agent {
void compete(const PaperAgent& competitor) const override {
std::cout << "I have won!" << std::endl;
}
//etc......
};
If I try to use these two methods by passing to the compete() function an Agent polymorphic instance (reference in this case) only the first one compiles. In the second case, the compiler complains that there is no such function as compete(const Agent&). I understand why this does not work, but is there any alternative out there that does not require dynamic_cast and is closer to the second case showed above in terms of design? Maybe a design pattern that I'm not aware of, or that I've never imagined could be used to emulate this?
Aucun commentaire:
Enregistrer un commentaire