Boost logo

Boost Users :

From: Peng Yu (pengyu.ut_at_[hidden])
Date: 2007-10-02 00:15:02


Hi,

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.

Thanks,
Peng

#include <iostream>

enum shape {
  circle,
  square // there might be many cases
};

template <shape, shape>
struct A {
  void doit() const;
};

//doit functions are defined for a majority number of shape
combinations (maybe not all, but could be defined for all---the bodies
of the functions not need can be empty).
// 3 case. There should be 4 doit's if we consider all combinations.
template <>
  void A<circle, circle>::doit() const {
    std::cout << "circle circle" << std::endl;
  }

template <>
  void A<circle, square>::doit() const {
    std::cout << "circle square" << std::endl;
  }

template <>
  void A<square, circle>::doit() const {
    std::cout << "square circle" << std::endl;
  }

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);
}


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