Re: RTTI and Multiple Dispatch
gwowen <gwowen@gmail.com> writes:
On Aug 2, 9:46??am, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
On Aug 2, 8:55??am, Christian Gollwitzer <aurio...@gmx.de> wrote:
Am 02.08.12 08:10, schrieb Gareth Owen:
What would people consider the most idiomatic way to create an
Rock-Paper-Scissors style game in C++
class Choice;
class Rock : public Choice;
class Scissors : public Choice;
class Paper : public Choice;
seems over the top. What's the difference between these classes?
I oversimplified. Suppose that these objects were more complicated
game pieces with their own movement characteristics
enum Type { MINE, ... };
class Spaceship {
public:
virtual void move();
virtual void launch();
int loc_x,loc_y;
virtual Type type() const = 0;
}
class Mine : public Spaceship;
virtual Type type() const { return MINE; }
class MineSweeper : public Spaceship;
class BattleShip : public Spaceship;
(idem)
(or use an attribute in Spaceship to avoid virtual calls overhead).
... with some fighting such that MineSweeper destroys Mine; Mine
destroys Battleship; Battleship destroys MineSweeper...
bool destroys(const Spaceship & s1, const Spaceship & s2)
{
const static bool d [][] =
{
{ true, false, ... }
...
};
return d[s1.type()][s2.type()]
}
or whatever implementation is suitable (You can put that in Spaceship.)
We're back to C here (treating enums as ints, but you can change this to
a switch). I know of no other good way to implement multiple dispatch in
C++. You could try:
class Mine : public Spaceship {
virtual bool destroys(const Spaceship & s) const
{
s.destroys_mine(s); // or ()
}
virtual bool destroys_mine(const Mine & m) const { ... }
virtual bool destroys_minesweeper(const MineSweeper & m) const { ... }
...
};
(with virtuals declared in Spaceship). You end up with N^2 + N methods
for N subclasses.
Common Lisp would have a great solution for this (defgeneric+defmethod).
Functional languages would use pattern-matching. But "classical" OO has
no good answer.
-- Alain.