Reputation: 405
Would it be possible for a lambda, which is inside a class X and defined outside that class X to magically use member variables of that class X ?
Like so:
struct Foo {
int x;
std::function<void(void)> f;
};
int main() {
Foo foo;
foo.x = 10;
foo.f = []() {
std::cout << x;
};
foo.f();
}
It would magically, without any context, use the "x" from the Foo struct.
I thought that because of a lambda being an anonymous struct, if I pass the object "foo" (the C way) in that function, it works, obviously:
struct Foo {
int x;
std::function<void(Foo&)> f;
};
int main() {
Foo foo;
foo.x = 10;
foo.f = [](Foo& me) {
std::cout << me.x;
};
foo.f(foo);
}
Is there any workaround to this ?
Upvotes: 1
Views: 55
Reputation: 345
without any context, you can do this
foo.f = [x=foo.x]() {
std::cout << x;
};
Upvotes: 2
Reputation: 476960
The natural approach would be to use a constructor:
struct Foo {
Foo() : f([this](){ std::cout << x; }) {}
int x;
std::function<void()> f;
};
Or perhaps a default member initializer:
struct Foo {
int x;
std::function<void()> f = [this]() { std::cout << x; };
};
(The function doesn't take any arguments, of course, so I changed the type of Foo::f
accordingly.)
The lambda cannot be "inherent to a class", since the lambda refers to an object of the class type, so every object must get its own lambda.
Usage:
Foo m;
m.x = 5;
m.f();
Upvotes: 3