如何在自身中使用lambda函数? [英] How can I use lambda function within itself?

查看:80
本文介绍了如何在自身中使用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);
    }
);

接受套接字后,我想重用处理程序(也就是lambda函数).这可能吗?有没有更好的方法可以做到这一点?

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?

推荐答案

您必须使用std::function<>(或类似方式)作为中介,将lambda的副本自身存储起来:

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);

但是您只能通过 reference 来完成;如果您试图通过价值来捕捉它,那将是行不通的.这意味着您必须将这种lambda的使用限制为按引用捕获才有意义的使用.因此,如果您在异步功能完成之前离开此作用域,它将中断.

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.

您的另一种选择是创建一个合适的函子而不是lambda.最终,lambda不能做所有事情.

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

这篇关于如何在自身中使用lambda函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆