In the code below, class A has a lambda as a data member, and a getter to this lambda. Is it possible to 'freeze' the local variables of the lambda to the values that are present when the lambda is returned by the getter?
In other words specifically in this example, is it possible to make the code print 6 instead of 150 even after the value of myA.b is changed?
#include <iostream>
#include <functional>
class A
{
double b;
std::function<double(double)> myFunction = [=] (double x)
{
double localb = b;
return localb*x;
};
public:
void set_b(double value){b = value;};
std::function<double(double)> get_myFunction(){return myFunction;};
};
int main()
{
A myA;
myA.set_b(2.0);
std::function<double(double)> retrievedFunction = myA.get_myFunction();
myA.set_b(50.0);
std::cout << retrievedFunction(3.0) << std::endl;
return 0;
}