best way to do variant visitation with lambdas

前端 未结 1 1618
挽巷
挽巷 2020-12-04 18:13

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 ,          


        
相关标签:
1条回答
  • 2020-12-04 18:50

    You could use variadic templates to take the lambdas, and build a variant visitor using inheritance. That would retain the compile time checks.

    template <typename ReturnType, typename... Lambdas>
    struct lambda_visitor : public static_visitor<ReturnType>, public Lambdas... {
        lambda_visitor(Lambdas... lambdas) : Lambdas(lambdas)... {}
    };
    

    And a little helper function to use argument type deduction (required for lambdas):

    template <typename ReturnType, typename... Lambdas>
    lambda_visitor<ReturnType, Lambdas...> 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<ReturnType, Lambdas...>(lambdas...);
    }
    

    Now you can make visitors like this:

    auto visitor = make_lambda_visitor<int>([](int) { return 42; },
                                            [](std::string) { return 17; },
                                            [](std::vector<int>) { 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.

    0 讨论(0)
提交回复
热议问题