Cast lambda to std::function with parameter pack

后端 未结 4 1004
北海茫月
北海茫月 2021-01-11 17:12

There are several questions on SO that relate to casting lambdas to std::functions, but I have yet to see one that uses a parameter pack for the argument list.

4条回答
  •  长发绾君心
    2021-01-11 18:00

    This fails:

    #include 
    
    template 
    void Functor(std::function f) {}
    
    int main(int argc, char * argv[]) {
        auto x = [] (int a, int b) { return a * b; };
        Functor(x);
        return 0;
    }
    

    because you're not specifying that the entirety of TArgs... is {int, int}. What you are doing is specifying that the first two types are {int, int}. Effectively, by providing those three types, we've turned the deduction problem into:

    template 
    void Functor(std::function f) {}
    
    int main(int argc, char * argv[]) {
        auto x = [] (int a, int b) { return a * b; };
        Functor(x);
        return 0;
    }
    

    This doesn't compile because a lambda isn't a std::function (or derived from one), which is the same reason you couldn't have called this without having provided any types to begin with.

    The non-variadic version doesn't have this problem, since you've provided all the types.


    But really, what you want is:

    template 
    void Functor(F ) {}
    

    This doesn't lose you any type safety. It's using std::function that loses type information, since that class template exists to type erase.

提交回复
热议问题