Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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;
like image 800
user357269 Avatar asked Aug 29 '16 12:08

user357269


People also ask

Can lambda function access local variables?

Local variables from outer scope can be captured inside Lambda in 2 modes i.e.

What does it mean to lambda capture this?

The lambda is capturing an outside variable. A lambda is a syntax for creating a class. Capturing a variable means that variable is passed to the constructor for that class. A lambda can specify whether it's passed by reference or by value.

How do you capture variables in lambda?

Capture clause A lambda can introduce new variables in its body (in C++14), and it can also access, or capture, variables from the surrounding scope. A lambda begins with the capture clause. It specifies which variables are captured, and whether the capture is by value or by reference.

What is the use of lambda function in C++?

C++ Lambda expression allows us to define anonymous function objects (functors) which can either be used inline or passed as an argument. Lambda expression was introduced in C++11 for creating anonymous functors in a more convenient and concise way.


2 Answers

auto plus( double a ) {
  using R = struct {
    double a;
    double operator()(double b)const{return b+a;}
  };
  return R{std::move(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.

like image 98
Yakk - Adam Nevraumont Avatar answered Oct 01 '22 01:10

Yakk - Adam Nevraumont


This is not how a lambda should be used.

The interface of a lambda is its function signature. Its captures should be considered an implementation detail and not be visible to the user.

If you want explicit access to the captures, write your own function object and expose the respective data members accordingly:

struct MyPlus {
    double a;
    MyPlus(double x) : a(x) {}
    double operator()(const double b)
    {
        return a+b;
    }
};

auto plus5 = MyPlus(5);
std::cout << plus5.a;
like image 40
ComicSansMS Avatar answered Oct 01 '22 03:10

ComicSansMS