c++0x: proper way to receive a lambda as parameter by reference

前端 未结 4 1050
醉酒成梦
醉酒成梦 2020-12-07 12:42

What is the right way to define a function that receives a int->int lambda parameter by reference?

void f(std::function< int(int) >&         


        
相关标签:
4条回答
  • 2020-12-07 13:31

    void f(auto& lambda);

    That's close. What will actually compile is:

    #include <cassert>
    
    /*constexpr optional*/ const auto f = [](auto &&lambda)
    {
      lambda();
      lambda();
    };
    
    int main()
    {
      int counter = 0;
      f([&]{ ++counter; });
      assert(counter == 2);
    }
    
    0 讨论(0)
  • 2020-12-07 13:37

    You cannot have an auto parameter. You basically have two options:

    Option #1: Use std::function as you have shown.

    Option #2: Use a template parameter:

    template<typename F>
    void f(F &lambda) { /* ... */}
    

    Option #2 may, in some cases, be more efficient, as it can avoid a potential heap allocation for the embedded lambda function object, but is only possible if f can be placed in a header as a template function. It may also increase compile times and I-cache footprint, as can any template. Note that it may have no effect as well, as if the lambda function object is small enough it may be represented inline in the std::function object.

    0 讨论(0)
  • 2020-12-07 13:37

    I would use template as:

    template<typename Functor>
    void f(Functor functor)
    {
       cout << functor(10) << endl;
    }
    
    int g(int x)
    {
        return x * x;
    }
    int main() 
    {
        auto lambda = [] (int x) { cout << x * 50 << endl; return x * 100; };
        f(lambda); //pass lambda
        f(g);      //pass function 
    }
    

    Output:

    500
    1000
    100
    

    Demo : http://www.ideone.com/EayVq

    0 讨论(0)
  • 2020-12-07 13:45

    I know it's been 7 years, but here's a way nobody else mentioned:

    void foo(void (*f)(int)){
        std::cout<<"foo"<<std::endl;
        f(1); // calls lambda which takes an int and returns void
    }
    int main(){
        foo([](int a){std::cout<<"lambda "<<a<<std::endl;});
    }
    

    Which outputs:

    foo
    lambda 1
    

    No need for templates or std::function

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