Alex Rivera | Logout

C++11 lambda as data member?

Asked 2011-07-06T19:37:14.323
80

Can lambdas be defined as data 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 lambdas 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've figured that if a lambda can be passed as a function argument, then maybe they can also be stored as a data member.

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

auto say_hello = [] { std::cout << "Hello"; };

struct Foo {
    using Bar = decltype(say_hello);
    Bar bar;
    Foo() : bar(say_hello) {}
};
Edit
Report

1 Answer

11
#include <functional>

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

void hello(const std::string & name) {
    std::cout << "Hello " << name << "!" << std::endl;
}

int test_foo() {
    Foo f;
    f.bar = std::bind(hello, "John");

    // Alternatively: 
    f.bar = []() { hello("John"); };
    f.bar();
}
answered 2011-07-06T19:40:40.877

Your Answer