Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 lambda as member variable?

Tags:

c++

c++11

lambda

Can lambda's be defined as class members?

For example, would it be possible to rewrite the code sample below using a lambda instead of a function object?

struct Foo {     std::function<void()> bar; }; 

The reason I wonder is because the following lambda's can be passed as arguments:

template<typename Lambda> void call_lambda(Lambda lambda) // what is the exact type here? {      lambda(); }  int test_foo() {     call_lambda([]() { std::cout << "lambda calling" << std::endl; }); } 

I figured that if a lambda can be passed as a function argument then maybe they can also be stored as a member variable.

After more tinkering I found that this works (but it's kind of pointless):

auto say_hello = [](){ std::cout << "Hello"; }; struct Foo {     typedef decltype(say_hello) Bar;     Bar bar;     Foo() : bar(say_hello) {} }; 
like image 882
StackedCrooked Avatar asked Jul 06 '11 19:07

StackedCrooked


People also ask

How do you pass a member variable to lambda?

To capture the member variables inside lambda function, capture the “this” pointer by value i.e. std::for_each(vec. begin(), vec. end(), [this](int element){ //.... }

What is the correct syntax for lambda expression in C++11?

Lambdas can both capture variables and accept input parameters. A parameter list (lambda declarator in the Standard syntax) is optional and in most aspects resembles the parameter list for a function. auto y = [] (int first, int second) { return first + second; };

How do you call a lambda in C++?

A lambda is also just a function object, so you need to have a () to call it, there is no way around it (except of course some function that invokes the lambda like std::invoke ). If you want you can drop the () after the capture list, because your lambda doesn't take any parameters.

Is Lamda a variable?

An environment variable is a pair of strings that is stored in a function's version-specific configuration. The Lambda runtime makes environment variables available to your code and sets additional environment variables that contain information about the function and invocation request.


1 Answers

A lambda just makes a function object, so, yes, you can initialize a function member with a lambda. Here is an example:

#include <functional> #include <cmath>  struct Example {    Example() {     lambda = [](double x) { return int(std::round(x)); };   };    std::function<int(double)> lambda;  }; 
like image 150
wjl Avatar answered Oct 10 '22 21:10

wjl