Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture a variable of this object in lambda?

Tags:

c++

lambda

c++14

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?

like image 289
aikhs Avatar asked Dec 22 '22 23:12

aikhs


2 Answers

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.

like image 167
songyuanyao Avatar answered Jan 11 '23 04:01

songyuanyao


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();
}
like image 41
Siliace Avatar answered Jan 11 '23 05:01

Siliace