How to create a variadic generic lambda?

后端 未结 3 1608
礼貌的吻别
礼貌的吻别 2020-12-12 15:02

Since C++14 we can use generic lambdas:

auto generic_lambda = [] (auto param) {};

This basically means that its call operator is templated

3条回答
  •  长情又很酷
    2020-12-12 15:43

    I am not sure what your intention is but instead of storing it in a std::function you can use the lambda itself to capture the params. This is an example discussed on the boost mailing list. It is used in the boost::hana implementation

    auto list = [](auto ...xs) {
        return [=](auto access) { return access(xs...); };
    };
    
    auto head = [](auto xs) {
        return xs([](auto first, auto ...rest) { return first; });
    };
    
    auto tail = [](auto xs) {
        return xs([](auto first, auto ...rest) { return list(rest...); });
    };
    
    auto length = [](auto xs) {
        return xs([](auto ...z) { return sizeof...(z); });
    };
    
    // etc...
    // then use it like
    
    auto three = length(list(1, '2', "3")); 
    

提交回复
热议问题