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

我在互联网上阅读了许多教程,解释如何使用 lambda 与标准库(如 std::find) ,他们都非常有趣,但我找不到任何解释如何使用我自己的函数 lambda。

例如:

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


return EXIT_SUCCESS;
}

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

35468 次浏览

Given that you probably also want to accept function pointers and function objects in addition to lambdas, you'll probably want to use templates to accept any argument with an operator(). This is what the std-functions like find do. It would look like this:

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

Note that this definition doesn't use any c++0x features, so it's completely backwards-compatible. It's only the call to the function using lambda expressions that's c++0x-specific.

If you don't want to template everything, you can do the following:

#include<functional>


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

I would like to contribute this simple but self-explanatory example. It shows how to pass "callable things" (functions, function objects, and lambdas) to a function or to an object.

// 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 ();


} // ()