Boost logo

Boost :

Subject: [boost] An open typeswitch using lambdas
From: Sumant Tambe (sutambe_at_[hidden])
Date: 2013-11-29 13:31:33


I would like to get feedback on a small typeswitch library I've been
working on for some time now. The library is designed to dispatch code
(lambdas) based on the actual value of boost::any, boost::variant, and also
general polymorphic hierarchies. An example is in order.

template <class Poly>
void test_poly(Poly& p)
    [](int i) { std::cout << "int = " << i << "\n"; },
    [](double d) { std::cout << "double = " << d << "\n"; },
    [](const std::string &s) { std::cout << "string = " << s << "\n"; },
    [](std::ostream &o) { std::cout << "found ostream" << "\n"; }

int main(void)
  std::ios_base &stream = std::cout;
  boost::any any(std::string("C++ Truths"));
  boost::variant<int, std::string> var("boost");
  double d = 9.99;

  test_poly(stream); // prints found stream
  test_poly(any); // prints string = C++ Truths
  test_poly(d); // prints double = 9.99
  test_poly(var) // prints string = boost

The implementation of the library is a little over 250 lines. Check it out
here: clang is the
only compiler I've been able to compile it with.

It resembles Scala's match statement. Scala's match is way more powerful
than what I've been able to achieve with C++ library emulation. It is also
quite similar to Stroustrup's "Open and Efficient Typeswitch for C++" ( A quick benchmark
shows that lambda-based typeswitch is about 4 to 5 times *slower*.

If there is sufficient interest, I would be thrilled to contribute this
library to boost. I believe it can be further generalized to support n-ary
method dispatching.


R/ Sumant

Boost list run by bdawes at, gregod at, cpdaniel at, john at