I have seen many answers on SO asking about capturing this
by reference but I have a different question. What if I want to capture a specific variable owned by this
object?
For example:
auto rel_pose = [this->_last_pose["main_pose"],&pose](Eigen::VectorXd pose1, Eigen::VectorXd pose2)
{
// Some code
return pose;
};
I want to capture the specific variable of this
by value and use it inside my lambda expression. Why this is not possible?
You can apply by-copy capture with an initializer (since C++14) (or by-reference capture with an initializer, depends on your demand), e.g.
auto rel_pose = [some_pose = this->_last_pose["main_pose"], &pose](Eigen::VectorXd pose1, Eigen::VectorXd pose2)
{
// Some code using some_pose
return pose;
};
Note that we can only capture identifiers in lambda, we can't capture expressions like this->_last_pose["main_pose"]
directly. The captures with an initializer just solve such issues straightforward.
It's possible:
struct S
{
int i = 7;
char c = 0;
};
int main(int argc, char* argv[])
{
S s;
auto l = [integer = s.i]() {
return integer;
};
return l();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With