代码之家  ›  专栏  ›  技术社区  ›  Andreas Bonini

如何声明接受lambda的函数?

  •  65
  • Andreas Bonini  · 技术社区  · 15 年前

    我在网上阅读了许多教程,解释了如何在标准库中使用lambda(例如 std::find ,它们都很有趣,但是我找不到任何解释如何为自己的函数使用lambda的方法。

    例如:

    int main()
    {
        int test = 5;
        LambdaTest([&](int a) { test += a; });
    
        return EXIT_SUCCESS;
    }
    

    我该怎么申报 LambdaTest ?第一个论点是什么类型的?然后,我如何才能调用传递给它的匿名函数-例如,“10”作为它的参数?

    3 回复  |  直到 10 年前
        1
  •  65
  •   sepp2k    15 年前

    假设除了lambda之外,您可能还希望接受函数指针和函数对象,那么您可能希望使用模板接受带有 operator() . 这就是标准函数find所做的。如下所示:

    template<typename Func>
    void LambdaTest(Func f) {
        f(10);
    }
    

    请注意,这个定义不使用任何C++0x特性,所以它完全向后兼容。这只是使用lambda表达式调用函数的函数,该表达式是C++ 0x特定的。

        2
  •  58
  •   doublep    15 年前

    如果不想将所有内容模板化,可以执行以下操作:

    void LambdaTest (const std::function <void (int)>& f)
    {
        ...
    }
    
        3
  •  6
  •   cibercitizen1    10 年前

    我想贡献这个简单但不言自明的例子。它演示了如何将“可调用的东西”(函数、函数对象和lambda)传递给函数或对象。

    // g++ -std=c++11 thisFile.cpp
    
    #include <iostream>
    #include <thread>
    
    using namespace std;
    
    // -----------------------------------------------------------------
    class Box {
    public:
      function<void(string)> theFunction; 
      bool funValid;
    
      Box () : funValid (false) { }
    
      void setFun (function<void(string)> f) {
        theFunction = f;
        funValid = true;
      }
    
      void callIt () {
        if ( ! funValid ) return;
        theFunction (" hello from Box ");
      }
    }; // class
    
    // -----------------------------------------------------------------
    class FunClass {
    public:
      string msg;
      FunClass (string m) :  msg (m) { }
      void operator() (string s) {
        cout << msg <<  s << endl; 
      }
    };
    
    // -----------------------------------------------------------------
    void f (string s) {
      cout << s << endl;
    } // ()
    
    // -----------------------------------------------------------------
    void call_it ( void (*pf) (string) ) {
      pf( "call_it: hello");
    } // ()
    
    // -----------------------------------------------------------------
    void call_it1 ( function<void(string)> pf ) {
      pf( "call_it1: hello");
    } // ()
    
    // -----------------------------------------------------------------
    int main() {
    
      int a = 1234;
    
      FunClass fc ( " christmas ");
    
      f("hello");
    
      call_it ( f );
    
      call_it1 ( f );
    
      // conversion ERROR: call_it ( [&] (string s) -> void { cout << s << a << endl; } );
    
      call_it1 ( [&] (string s) -> void { cout << s << a << endl; } );
    
      Box ca;
    
      ca.callIt ();
    
      ca.setFun (f);
    
      ca.callIt ();
    
      ca.setFun ( [&] (string s) -> void { cout << s << a << endl; } );
    
      ca.callIt ();
    
      ca.setFun (fc);
    
      ca.callIt ();
    
    } // ()