user357269 user357269 - 3 months ago 9
C++ Question

Is it possible to access (read only) the variables captured by a lambda?

Is it possible to access (read only) the variables captured by a lambda?

This doesn't work:

std::function<double (const double)> plus (const double a) {
return [a] (const double b) -> double {
return a+b;
};
}

auto plus5 = plus(5);
cout << plus5.a << endl;

Answer
auto plus( double a ) {
  using R = struct {
    double a;
    double operator()(double b)const{return b+a;}
  };
  return R{a};
}

live example.

Please note that a std::function is not a lambda, and lambda is not a std::function. They work with each other, but using one term to refer to the other is the opposite of helpful.

Comments