c++ 实现lambda 回调
Lambda本质上就是一个匿名的仿函数,因此模板函数里直接使用 operator (),可以用lambda 结合template作为回调函数。如果需要全局缓存就用到: std::tr1::function<> 。
代码如下:
h 文件:
#include using namespace std;
using namespace rld;class MyFunctionClass {
public:MyFunctionClass();~MyFunctionClass();templatevoid functionTest1(const T &t);void functionTest2(const tr1::function &f);templatevoid setFunction1(const T &t);void setFunction2(const tr1::function &fun2);void TestFunc1();void TestFunc2();private:tr1::function mf1_;tr1::function mf2_;};
cpp 文件:
#includeMyFunctionClass::MyFunctionClass()
{
}MyFunctionClass::~MyFunctionClass()
{
}template
inline void MyFunctionClass::functionTest1(const T &t)
{string msg = "test function ";msg.append(__FUNCTION__);t(msg);
}template
inline void MyFunctionClass::setFunction1(const T &t)
{mf1_ = t;
}
void MyFunctionClass::functionTest2(const tr1::function &f)
{string msg = "my fun tr1 f1";f(msg, 88);
}void MyFunctionClass::setFunction2(const tr1::function &fun2)
{mf2_ = fun2;
}void MyFunctionClass::TestFunc1()
{string parma = "test my tr1 fun1";mf1_(parma);
}void MyFunctionClass::TestFunc2()
{string param = "teste my tr1 fun2";mf2_(param);}void TestLambdaFunction()
{unique_ptr myTest(new MyFunctionClass());myTest->functionTest1([&](string &msg)->string {RLD_TAG_LOG(RLD_LERROR) << msg;return "over";});myTest->functionTest2([&](string &str, int data)->string {RLD_TAG_LOG(RLD_INFO) << str <setFunction1([](string &msg1)->string {RLD_TAG_LOG(RLD_INFO) << msg1;string result = "over";return result;});myTest->TestFunc1();myTest->setFunction2([](string &msg1)->string {RLD_TAG_LOG(RLD_INFO) << msg1;return "ch";});myTest->TestFunc2();}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
