如何从lambda-functor的体中增加变量?

St.*_*rio 8 c++ lambda c++11 c++14

我试图从lambda表达式增加一个局部变量:

#include <iostream>

template<typename T>
T foo(T t){
    T temp{};
    [temp]() -> void { 
        temp++; 
    }();
    return temp;
}

int main()
{
    std::cout<< foo(10) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

DEMO

但得到以下错误:

main.cpp: In instantiation of 'foo(T)::<lambda()> [with T = int]':

main.cpp:6:6:   required from 'struct foo(T) [with T = int]::<lambda()>'

main.cpp:8:6:   required from 'T foo(T) [with T = int]'

main.cpp:14:23:   required from here

main.cpp:7:13: error: increment of read-only variable 'temp'

         temp++; 

             ^
Run Code Online (Sandbox Code Playgroud)

在c ++ 11/14中是否有一些解决方法?

son*_*yao 7

temp 当它被非可变lambda中的副本捕获时,不能被修改.

您可以temp通过参考捕获:

template<typename T>
T foo(T t){
    T temp{};
    [&temp]() -> void { 
        temp++; 
    }();
    return temp;
}
Run Code Online (Sandbox Code Playgroud)


Tar*_*ama 5

如果要按值捕获变量并对其进行修改,则需要标记lambda mutable

[temp]() mutable -> void {
//       ^^^^^^^ 
    temp++; 
}();
Run Code Online (Sandbox Code Playgroud)

这允许主体修改由值捕获的参数,并调用其非常量成员函数

  • 我明白了,谢谢。最好提及一下,我认为这与OP的初衷相抵触。 (2认同)