Cast lambda to std::function with parameter pack

后端 未结 4 1012
北海茫月
北海茫月 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 17:42

    Here is a solution that will let you call functor without specifying it's template argument:

    #include 
    #include 
    
    template  struct Fun_trait {};
    
    template 
    struct Fun_trait Ret>
    {
        using F = std::function Ret>;
    };
    
    
    template 
    void functor(std::function f) {}
    
    template 
    std::void_t
    functor(F f)
    {
        return functor::F>(f);
    };
    
    
    int main(int argc, char * argv[])
    {
        auto x = [] (int a, int b) { return a * b; };
    
        // nice and easy:
        functor(x); 
    
        return 0;
    }
    

    This is just a lazy first draft to get you started. You need to expand it to support forwarding and non-const operator().


    It works in 2 stages:

    1st we have Fun_trait who - for pointer method types (e.g. the operator() of a lambda) - has defined an alias F for the required std::function argument type.

    Next we have a overload of your function functor which via SFINAE with std::void_t kicks in only for functors with a non-overloaded operator() (e.g. a lambda) and then using the above trait calls the main function functor with the correct template argument deduced.

提交回复
热议问题