I want to inline visitation of variant types with lambdas. At the moment i have the following code:
struct Foo {
boost::variant< boost::blank , int ,
You could use variadic templates to take the lambdas, and build a variant visitor using inheritance. That would retain the compile time checks.
template
struct lambda_visitor : public static_visitor, public Lambdas... {
lambda_visitor(Lambdas... lambdas) : Lambdas(lambdas)... {}
};
And a little helper function to use argument type deduction (required for lambdas):
template
lambda_visitor make_lambda_visitor(Lambdas... lambdas) {
return { lambdas... };
// you can use the following instead if your compiler doesn't
// support list-initialization yet
// return lambda_visitor(lambdas...);
}
Now you can make visitors like this:
auto visitor = make_lambda_visitor([](int) { return 42; },
[](std::string) { return 17; },
[](std::vector) { return 23; });
Note: due to a detail of the overload resolution process that I wasn't aware of, this elegant solution causes weird ambiguity errors :(
See the follow-up question for the fix.