如何声明一个接受lambda的函数?

时间:2010-05-30 12:20:17

标签: c++ lambda c++11

我在互联网上阅读了许多教程,这些教程解释了如何在标准库中使用lambdas(例如std::find),它们都非常有趣,但我找不到任何解释我如何使用的内容一个lambda用于我自己的功能。

例如:

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

    return EXIT_SUCCESS;
}

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

3 个答案:

答案 0 :(得分:67)

鉴于您可能还想接受除lambdas之外的函数指针和函数对象,您可能希望使用模板接受operator()的任何参数。这就像find这样的std函数。它看起来像这样:

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

请注意,此定义不使用任何c ++ 0x功能,因此它完全向后兼容。它只是使用lambda表达式调用函数,该表达式是c ++ 0x特定的。

答案 1 :(得分:60)

如果您不想模仿所有内容,可以执行以下操作:

void LambdaTest (const std::function <void (int)>& f)
{
    ...
}

答案 2 :(得分:7)

我想提供这个简单但不言自明的例子。它展示了如何传递&#34;可赎回的东西&#34; (函数,函数对象和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 ();

} // ()
相关问题