I have several methods in my class. I want a lambda in one method to call another method of the class. But I don't want to capture this
so that I can limit the scope of what the lambda has access to. Is this possible?
I've tried to capture the method as [&method = Class::my_method]
or variations of that but there's something I'm missing.
#include <iostream>
class Hello
{
public:
double test_lambda(const double in)
{
// If I capture `this` instead, then this works fine
const auto a_lambda = [add_number = this->add_number](const double in)
{
return add_number(in);
};
return a_lambda(in);
}
private:
double add_number(const double in)
{
return in + 2.0;
}
};
int main()
{
Hello h;
std::cout << "Hello World: " << h.test_lambda(4.0); // Expect 6
return 0;
}
I would hope that I could capture a method like this but I'm not sure if it's possible.
The reason I want to do this based on a coding preference to limit what the lambda has access to. For example, if I wanted the lambda to mutate members of a class, I could do
another_lambda = [this](){
m_value_one = 1.0;
m_value_two = 2.0;
// This has access to other members
}
Or to limit what the lambda can mutate, I can do:
another_lambda = [&value_one = this->m_value_one, &value_two = this->m_value_two](){
value_one = 1.0;
value_two = 2.0;
// This does not have access to other members
}
The post is asking whether the same can be done with class methods, but it seems that it cannot.