Use a lambda as a parameter for a C++ function

后端 未结 3 1304
南笙
南笙 2020-12-09 16:04

I would like to use a lambda as a parameter for a C++ function, but I don\'t know which type to specify in the function declaration. What I would like to do is this:

相关标签:
3条回答
  • 2020-12-09 16:11

    You have two choices, basically.

    Make it a template:

    template<typename T>
    void myFunction(T&& lambda){
    }
    

    or, if you do not want (or can't) do that, you can use type-erased std::function:

    void myFunction(std::function<void()> const& lambda){
    }
    

    Conversely, your attempt with auto would've been correct under the concepts TS as currently implemented in gcc, where it'd be an abbreviated template.

    // hypothetical C++2x code
    void myFunction(auto&& lambda){
    }
    

    or with a concept:

    // hypothetical C++2x code
    void myFunction(Callable&& lambda){
    }
    
    0 讨论(0)
  • 2020-12-09 16:21

    You have 2 ways: make your function template:

    template <typename F>
    void myFunction(F&& lambda){
        //some things
    }
    

    or erase type with std::function

    void myFunction(const std::function<void()/* type of your lamdba::operator()*/>& f){
        //some things
    }
    
    0 讨论(0)
  • 2020-12-09 16:22

    If this is an inline function, prefer a template, as in

    template<typename Func>
    void myFunction(Func const&lambda)
    {
        //some things
    }
    

    because it binds to anything that makes sense (and will cause compiler error for anything else), including lambdas, instances of named classes, and std::function<> objects.

    On the other hand, if this function is not inline, i.e. implemented in some compilation unit, you cannot use a generic template but must use a specified type, which is best taken a std::function<> object and passed via reference.

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