0

It's the first time I use lambda functions in C++ and I need to pass a value to use inside the body of a lambda function:

in the code above I need to pass int parameter seq_msg:

void do_connect(tcp::resolver::iterator endpoint_iterator, int seq_msg)
{
    boost::asio::async_connect(socket_, endpoint_iterator, [this](boost::system::error_code ec, tcp::resolver::iterator)
    {
        if (!ec)
        {
            send_message(seq_msg);

            do_read_header();
        }           
    });
}

2 Answers 2

6

I guess you should capture it by value and change:

[this]

to:

[this, seq_msg]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use bind

void do_connect(tcp::resolver::iterator endpoint_iterator, int seq_msg)
{
    auto cb = [this](boost::system::error_code ec, tcp::resolver::iterator, int seq)
    {
        if (!ec)
        {
            send_message(seq_msg);

            do_read_header();
        }           
    }
    boost::asio::async_connect(socket_, endpoint_iterator, std::bind(cb, std::placeholders::_1, std::placeholders::_2, seq_msg) );
}

Or just capture seq_msg

2 Comments

Thank you all. I tested the options and both work. Now, I just need to understand if there is something important difference between them.
If you are using lambda as a callback then no doubt that capture one extra parameter is much easier. Bind approach allow you to create function object from other class functions, pointers to function or another function objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.