author:
- luixiao1223
title: 附录A
A.5 Lambda Functions
举例
[]{
do_stuff();
do_more_stuff();
}(); // call
参数
std::vector<int> data=make_data();
std::for_each(data.begin(),data.end(),[](inti){std::cout<<i<<"\n";});
如果你的函数体有单个的返回路径,则不用声明返回值.编译器可以推导返回值.(PS:在C++11上,实测多行带条件的多个返回也可以推导)
std::condition_variable cond;
bool data_ready;
std::mutex m;
void wait_for_data()
{
std::unique_lock<std::mutex> lk(m);
cond.wait(lk,[]{return data_ready;});
}
手动设置返回值,多个路劲返回.
// cond.wait(lk,[]()->bool{return data_ready;});
cond.wait(lk,[]()->bool{
if(data_ready)
{
std::cout<<”Data ready”<<std::endl;
return true;
}
else
{
std::cout<<”Data not ready, resuming wait”<<std::endl;
return false;
}
});
Lambda functions that reference local variables.
拷贝capture所有的local变量
std::function<int(int)> make_offseter(int offset)
{
return [=](int j){return offset+j;};
}
int main()
{
std::function<int(int)> offset_42=make_offseter(42);
std::function<int(int)> offset_123=make_offseter(123);
std::cout<<offset_42(12)<<”,“<<offset_123(12)<<std::endl;
std::cout<<offset_42(12)<<”,“<<offset_123(12)<<std::endl;
}
引用capture所有的local变量
it’s undefined behavior to call the lambda once the variables it
references have been destroyed by exiting the function or block scope to
which they belong, just as it’s undefined behavior to reference a
variable that has already been destroyed in any other circumstance.
int main()
{
int offset=42;
std::function<int(int)> offset_a=[&](int j){return offset+j;};
offset=123;
std::function<int(int)> offset_b=[&](int j){return offset+j;};
std::cout<<offset_a(12)<<”,”<<offset_b(12)<<std::endl;
offset=99;
std::cout<<offset_a(12)<<”,”<<offset_b(12)<<std::endl;
}
默认拷贝捕捉,但是另外几个例外用引用捕捉
int main()
{
int i=1234,j=5678,k=9;
std::function<int()> f=[=,&j,&k]{return i+j+k;};
i=1;
j=2;
k=3;
std::cout<<f()<<std::endl;
}
默认引用捕捉,另外几个例外用拷贝捕捉
int main()
{
int i=1234,j=5678,k=9;
std::function<int()> f=[&,j,k]{return i+j+k;};
i=1;
j=2;
k=3;
std::cout<<f()<<std::endl;
}
捕捉仅仅几个变量
int main()
{
int i=1234,j=5678,k=9;
std::function<int()> f=[&i,j,&k]{return i+j+k;};
i=1;
j=2;
k=3;
std::cout<<f()<<std::endl;
}
捕捉类对象中的成员
struct X
{
int some_data;
void foo(std::vector<int>& vec)
{
std::for_each(vec.begin(),vec.end(),
[this](int& i){i+=some_data;});
}
};
C++14 通用lambda
generic lambda
generic lamdas , where the parameter types are declared as auto
rather than a specified type.
auto f=[](auto x){ std::cout<<”x=”<<x<<std::endl;};
f(42); // x is of type int; outputs “x=42”
f(“hello”); // x is of type const char*; outputs “x=hello”
generalized captures
you can capture the results of expressions.( Most commonly this can be
used to capture move-only types by moving them, rather than having to
capture by reference)
std::future<int> spawn_async_task(){
std::promise<int> p;
auto f=p.get_future();
std::thread t([p=std::move(p)](){ p.set_value(find_the_answer());});
t.detach();
return f;
}