Nat Goodspeed wrote:
Peng Yu wrote:
I have the following program, which uses a switch statement to call different template functions. The example is simple, but as the number of shapes increase, the switch statement might be very hard to maintain.
I'm looking for a more general solution (maybe using mpl, not sure), such that the switch statement can be automatically generated, therefore, more maintainable.
void f(shape s1, shape s2) { // each defined shape-combination corresponds to one case // I want to generalize the code by using boost::mpl // (or some other packages if applicable) switch(s1 << 8 | s2) { case circle << 8 | circle: A
().doit(); break; case circle << 8 | square: A ().doit(); break; case square << 8 | circle: A ().doit(); break; default: std::cout << "not defined" << std::endl; } } int main() { f(circle, circle); f(circle, square); f(square, circle); f(square, square); }
I believe this is essentially a double-dispatch problem, though you're using enum values rather than distinct subclass types. Scott Meyers talks about double dispatch (in More Effective C++? I don't have it with me). At that point he was advocating a map of target functions, keyed by type pairs.
Does MPL give us a more robust way to address multiple dispatch?
I think that was "Modern C++ Design" by Alexandrescu. Jeff Flinn