我在互联网上读了很多教程,它们解释了如何在标准库(如std::find
)中使用lambda,它们都非常有趣,但我找不到任何解释如何将lambda用于我自己的函数的教程。
例如:
int main()
{
int test = 5;
LambdaTest([&](int a) { test += a; });
return EXIT_SUCCESS;
}
我应该如何声明LambdaTest
?它的第一个参数的类型是什么?然后,我如何调用传递给它的匿名函数-例如- "10“作为其参数?
发布于 2010-05-30 20:25:01
考虑到除了operator()
之外,您可能还希望接受函数指针和函数对象,那么您可能希望使用模板来接受带有lambda的任何参数。这就是像find这样的std函数所做的事情。它看起来像这样:
template<typename Func>
void LambdaTest(Func f) {
f(10);
}
注意,这个定义没有使用任何c++0x特性,因此它是完全向后兼容的。只有使用lambda表达式的函数调用才是特定于c++0x的。
发布于 2010-05-30 20:32:05
如果您不想将所有内容都模板化,可以执行以下操作:
#include<functional>
void LambdaTest (const std::function <void (int)>& f)
{
...
}
发布于 2014-12-24 06:35:43
我想贡献这个简单但不言自明的例子。它展示了如何将“可调用的东西”(函数、函数对象和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 ();
} // ()
https://stackoverflow.com/questions/2938571
复制相似问题