boost::variant and lambda functions in C++11

Released some time ago new C++11 standard introduced lambda functions - long anticipated and exciting feature. On the other hand, boost::variant has been around for awhile and is used successfully in many projects. The recommended and type-safe way of applying type-specific logic to values of variant types is using visitor pattern. However, a visitor is a functor, which until now should have been defined separately, in a class of its own. It would be nice if we could use lambda functions to achieve the same functionality. Thanks to some clever folks on StackTrace, we can do exactly that:

  1. /// Define helper classes and function
  2. template <typename ReturnT, typename... Lambdas>
  3. struct lambda_visitor;
  4.  
  5. template <typename ReturnT, typename L1, typename... Lambdas>
  6. struct lambda_visitor< ReturnT, L1 , Lambdas...> : public L1, public lambda_visitor<ReturnT, Lambdas...>
  7. {
  8.     using L1::operator();
  9.     using lambda_visitor< ReturnT , Lambdas...>::operator();
  10.     lambda_visitor(L1 l1, Lambdas... lambdas) 
  11.       : L1(l1), lambda_visitor< ReturnT , Lambdas...> (lambdas...)
  12.     {}
  13. };
  14.  
  15. template <typename ReturnT, typename L1>
  16. struct lambda_visitor<ReturnT, L1> : public L1, public boost::static_visitor<ReturnT>
  17. {
  18.     using L1::operator();
  19.     lambda_visitor(L1 l1) 
  20.       :  L1(l1), boost::static_visitor<ReturnT>()
  21.     {}
  22. };
  23.  
  24. template <typename ReturnT>
  25. struct lambda_visitor<ReturnT> : public boost::static_visitor<ReturnT> 
  26. {
  27.  
  28.     lambda_visitor() : boost::static_visitor<ReturnT>() {}
  29. };
  30.  
  31. template <typename ReturnT, typename... Lambdas>
  32. lambda_visitor<ReturnT, Lambdas...> make_lambda_visitor(Lambdas... lambdas)
  33. {
  34.     return { lambdas... };
  35. }
  36.  
  37.  
  38. /// Now we can use lambdas directly
  39. auto val = boost::variant<std::string, int>("Test");
  40. auto visitor = make_lambda_visitor<void>(
  41.                 [](const std::string & str) { std::cout << str; },
  42.                 [](const int& sec) { std::cout << sec; });
  43. boost::apply_visitor(visitor, val);

Relevant source.

Add new comment

Subscribe to Comments for "boost::variant and lambda functions in C++11"