Re: Multimethods idioms and library support
On 22 Feb., itaj sherman wrote:
[snip]
I won't get into descibing the real module I was working on that
triggered my problem, but I can describe a very short example to
demonstrate it.
For example:
An animal kingdom module defines base classes Carnivour and Prey.
And a multimethod:
void hunt( Carnivour const&, Prey& );
I want to enable users of my module to have their classes inherited
from Carnivour or Prey, and enable them to define override functions
for hunt special for their types.
A certain user then create his classes: Lion, Anaconda and Bear
derived from Carnivour, Giraffe and Gazelle derived from Prey.
He also wants to override the possible hunt implementation.
The following code demonstrates how I wished it could be written
(based on the proposition in "The Design and Evolution of C++ Bjarne
Stroustrup").
I'm looking for a library that will support such multimethods.
Basically replacing the hipothetic language syntax with some library
constrcuts. But enable the same general construction and dependency of
the module and user code.
[snip]
The following should scale okay.
#include <iostream>
class CarnivourDispatch;
class Prey
{
public:
virtual void dispatchMe (CarnivourDispatch*) = 0;
};
class Carnivour
{
public:
virtual void hunt (Prey& prey) = 0;
};
class Giraffe;
class Gazelle;
class CarnivourDispatch : public Carnivour
{
public:
virtual void hunt (Prey& prey)
{
prey.dispatchMe (this);
}
virtual void _hunt (Gazelle&) = 0;
virtual void _hunt (Giraffe&) = 0;
};
class Lion: public CarnivourDispatch
{
protected:
virtual void _hunt (Gazelle& Gazelle)
{
std::cout << "Lion jumps on gazelle and bites its neck.";
}
virtual void _hunt (Giraffe&)
{
std::cout << "Lion bites giraffe's ass";
}
};
class Giraffe : public Prey
{
public:
void dispatchMe (CarnivourDispatch* Hunter)
{
Hunter->_hunt (*this);
}
};
class Gazelle : public Prey
{
public:
void dispatchMe (CarnivourDispatch* Hunter)
{
Hunter->_hunt (*this);
}
};
//main.cpp
int main()
{
Carnivour* carnivour = new Lion;
Prey* prey1 = new Gazelle;
Prey* prey2 = new Giraffe;
carnivour->hunt (*prey1);
carnivour->hunt (*prey2);
}
Probably the dispatchMe-methods in Prey derived class should be added
by a template, but I tried to keep it simple.
Regards,
Stuart