Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use lambda function within itself?

Tags:

c++

c++11

lambda

I have this code and don't know if what I would like to achieve is possible.

_acceptor.async_accept(
    _connections.back()->socket(),
    [this](const boost::system::error_code& ec)
    {
        _connections.push_back(std::make_shared<TcpConnection>(_acceptor.get_io_service()));
        _acceptor.async_accept(_connections.back()->socket(), this_lambda_function);
    }
);

Once a socket is accepted, I would like to reuse the handler (aka the lambda function). Is this possible? Is there a better way to accomplish this?

like image 971
flumpb Avatar asked Apr 08 '12 19:04

flumpb


People also ask

Can a lambda function call itself?

A recursive lambda expression is the process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily.

Can AWS Lambda trigger itself?

Just upload your code, and Lambda takes care of everything required to run and scale your code with high availability. You can set up your code to automatically trigger from other AWS services or call it directly from any web or mobile app.

Can lambda function call itself python?

Bookmark this question. Show activity on this post. A regular function can contain a call to itself in its definition, no problem.


1 Answers

You have to store a copy of the lambda in itself, using std::function<> (or something similar) as an intermediary:

std::function<void(const boost::system::error_code&)> func;
func = [&func, this](const boost::system::error_code& ec)
{
    _connections.push_back(std::make_shared<TcpConnection>(_acceptor.get_io_service()));
    _acceptor.async_accept(_connections.back()->socket(), func);
}

_acceptor.async_accept(_connections.back()->socket(), func);

But you can only do it by reference; if you try to capture it by value, it won't work. This means you have to limit the usage of such a lambda to uses were capture-by-reference will make sense. So if you leave this scope before your async function is finished, it'll break.

Your other alternative is to create a proper functor rather than a lambda. Ultimately, lambdas can't do everything.

like image 97
Nicol Bolas Avatar answered Nov 03 '22 09:11

Nicol Bolas