Only non-static members have access to this
. However, the problem is that you cannot declare a non-static
lambda member variable, you can only declare static constexpr
lambda members. In other words:
class Foo {
auto lambda1 = [](){}; // fails to compile
static constexpr lambda2 = [](){}; // fine, but no access to this
static constexpr lambda3 = [this](){}; // fails to compile
static constexpr lambda4 = [](Foo* self){}; // works
};
However, what you can do is create non-static
std::function
member variable that captures this
:
class Foo {
std::function<void()> func = [this](){}; // works
};
The drawback is that this stores the pointer this
in the func
object, which seems a bit redundant, and also makes it problematic to move an object of type Foo
(as that would invalidate the captured this
pointer). Furthermore, you cannot capture a variable from another member function if the lambda is declared outside that member function.
But as already mentioned by others in the comments, do you even need a lambda at this point? You can just create an extra (private
) member function instead of a lambda, and pass it references to any variables you want it to have access to.
I don't think this is what you meant, but you can of course pass a lambda from one member function to another:
class Foo {
public:
void func1() {
auto lambda = [&, this](){};
func2(lambda);
}
void func2(auto& lambda) {
lambda();
}
};
Be aware that whatever is captured by reference in func1()
is only valid for the lifetime of the call to func1()
. So this is invalid:
class Foo {
std::function<void()> lambda;
public:
void func1() {
lambda = [&, this](){};
}
void func2() {
lambda();
}
};
Foo foo;
foo.func1();
foo.func2(); // undefined behavior