Boost logo

Boost Users :

From: Jeff Flinn (TriumphSprint2000_at_[hidden])
Date: 2007-10-02 13:43:56


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<circle, circle>().doit();
>> break;
>> case circle << 8 | square:
>> A<circle, square>().doit();
>> break;
>> case square << 8 | circle:
>> A<square, circle>().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


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net