Boost logo

Boost :

From: Andrey Semashev (andysem_at_[hidden])
Date: 2007-02-02 16:00:04


Hello Steven,

Friday, February 2, 2007, 10:16:54 PM, you wrote:

> AMDG

> Is there any interest in a function template that generates a switch
> statement?

> struct f {
> typedef void result_type;
> void operator()(mpl::int_<0>) const {
> std::cout << "2" << std::endl;
> }
> void operator()(mpl::int_<1>) const {
> std::cout << "1" << std::endl;
> }
> void operator()(mpl::int_<5>) const {
> std::cout << "0" << std::endl;
> }
> };

> int main() {
> typedef mpl::vector<mpl::int_<0>, mpl::int_<1>, mpl::int_<5> > cases;
> switch<cases>(5, f()); //prints 0
> try {
> switch<cases>(3, f());
> } catch(bad_switch&) {}
> }

Interesting. It would be much better if it is integrated with
Boost.Lambda. Something like this:

switch_< cases >(5,
  var(cout) << "2\n",
  var(cout) << "1\n",
  var(cout) << "0\n",
  var(cout) << "default case - may be optional\n"
  );

In fact, it would be even greater to extend the language switch
capabilities to type-selection and non-integral type constants with
fusion containers or tuples. Something like:

typedef fusion::vector< int, int, string, double > cases_t;
cases_t cases(2, 5, "a string", 7.3);

list< any > container1; // assume it's filled

for_each(container1.begin(), container1.end(),
  switch_(_1,
    cases,
    var(cout) << "The value is int and equals 2\n",
    var(cout) << "The value is int and equals 5\n",
    var(cout) << "The value is string 'a string'\n",
    var(cout) << "The value is double and equals 7.3\n",
    var(cout) << "The default branch\n");

vector< int > container2; // assume it's filled
for_each(container2.begin(), container2.end(),
  switch_(_1,
    cases,
    var(cout) << "The value is int and equals 2\n",
    var(cout) << "The value is int and equals 5\n");
    // other cases are not significant since they won't happen
  

-- 
Best regards,
 Andrey                            mailto:andysem_at_[hidden]

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk