patterncppMinor
Multiple dispatch with variant and multi visitation in C++
Viewed 0 times
variantmultiwithvisitationdispatchmultipleand
Problem
The following program is a demonstration of variant and double visitation used to obtain double dispatch between the elements of two inhomogeneous containers. Most of the work is done at compile time. What do you think about it compared to the dynamic version in explained in Wikipedia?
boost::variant does not employ variadic templates and has a hand coded limit to 20 different types which can be easily extended to 50 but not beyond. Is it a crazy idea to use this pattern (with an appropriate variant implementation) with more than 50 types, say 100 spaceships and 10 different asteroids or so?#include
#include
#include "boost/variant.hpp"
using std::cout;
using std::endl;
////////// some basic objects
class SpaceShip {};
class ApolloSpacecraft : public SpaceShip {};
class Asteroid {
public:
void CollideWith(SpaceShip&)
{ cout {
template
void operator()( A & a, S & s) const { a.CollideWith(s);}
};
////////// demo
int main() {
std::vector> asteroids;
asteroids.emplace_back(Asteroid());
asteroids.emplace_back(ExplodingAsteroid());
std::vector> spaceships;
spaceships.emplace_back(SpaceShip());
spaceships.emplace_back(ApolloSpacecraft());
for (auto & a : asteroids) {
for (auto & s : spaceships) {
boost::apply_visitor(CollideVisitor(), a, s);
}
}
return 0;
}Solution
It's a good example of multimethods in C++. But you should be aware that
But, to be serious, there's an even bigger problem: extension. You would like to
Your solution needs to have
variant takes at least as much space as the biggest of its argument. It's done so to minimize overhead of walking an additional pointer. Probably, you need a variant with another allocation policy, as asteroids and spaceships are quite numerous. But, to be serious, there's an even bigger problem: extension. You would like to
- define new functions that do something with asteroids, spaceships or tuples of them;
- define new types of asteroids and spaceships;
- modify code only locally.
Your solution needs to have
variant in several places of your code in addition to defining a new classes for new types of game objects. That's a non-local change.Context
StackExchange Code Review Q#52495, answer score: 2
Revisions (0)
No revisions yet.