简体   繁体   English

C ++ 14使用capture-specifier在lambda函数内增加一个值

[英]C++14 increment a value inside of lambda function with capture-specifier

My task is to write a lambda function which increment a value, but I have to use value = 0 capture-specifier. 我的任务是编写一个增加值的lambda函数,但我必须使用value = 0 capture-specifier。 I'm thinking about the following function: 我正在考虑以下功能:

auto lambda = [value = 0]{return ++value}

When this function is called it has to give an incremented value every time. 调用此函数时,每次都必须给出递增的值。 But I know this implementation is wrong, because it's passed by value. 但我知道这个实现是错误的,因为它是通过值传递的。 How can I do this in C++14? 我怎么能用C ++ 14做到这一点?

你需要使lambda变为可变:

auto lambda = [value = 0]() mutable {return ++value;};

You don't need a capture: 你不需要捕获:

[]{ static int i=0; return ++i; }

Is all you need. 是你所需要的全部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM