C++11 “overloaded lambda” with variadic template and variable capture

前端 未结 1 629
轮回少年
轮回少年 2020-11-30 11:34

I\'m investigating a C++11 idiom which might be called \"overloaded lambda\":

  • http://cpptruths.blogspot.com/2014/05/fun-with-lambdas-c14-style-part-2.html
1条回答
  •  时光说笑
    2020-11-30 12:11

    Overload resolution works only for functions that exist in a common scope. This means that the second implementation fails to find the second overload because you don't import function call operators from overload into overload.

    However, a non-capturing lambda type defines a conversion operator to a function pointer with the same signature as the lambda's function call operator. This conversion operator can be found by name lookup, and this is what gets invoked when you remove the capturing part.

    The correct implementation, that works for both capturing and non-capturing lambdas, and that always calls operator() instead of a conversion operator, should look as follows:

    template 
    struct overload;
    
    template 
    struct overload : F0, overload
    {
        overload(F0 f0, Frest... rest) : F0(f0), overload(rest...) {}
    
        using F0::operator();
        using overload::operator();
    };
    
    template 
    struct overload : F0
    {
        overload(F0 f0) : F0(f0) {}
    
        using F0::operator();
    };
    
    template 
    auto make_overload(Fs... fs)
    {
        return overload(fs...);
    }
    

    DEMO

    In c++17, with class template argument deduction and pack expansion of using declarations in place, the above implementation can be simplified to:

    template  
    struct overload : Ts... { using Ts::operator()...; };
    
    template 
    overload(Ts...) -> overload;
    

    DEMO 2

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