How to create a variadic generic lambda?

后端 未结 3 1589
礼貌的吻别
礼貌的吻别 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:38

    Consider this

    #include 
    
        namespace {
    
            auto out_ = [] ( const auto & val_) 
            {
                std::cout << val_;
                return out_ ;
            };
    
            auto print = [](auto first_param, auto... params)
            {
                out_(first_param);
    
                // if there are  more params
                if constexpr (sizeof...(params) > 0) {
                    // recurse
                    print(params...);
                }
                    return print;
            };
        }
    
    int main()
    {
        print("Hello ")("from ")("GCC ")(__VERSION__)(" !"); 
    }
    

    (wandbox here) This "print" lambda is:

    • Variadic
    • Recursive
    • Generic
    • Fast

    And no templates in sight. (just underneath :) ) No C++ code that looks like radio noise. Simple, clean and most importantly:

    • Easy to maintain

    No wonder "it feels like a new language".

提交回复
热议问题