如何在自身中使用lambda函数?

编程入门 行业动态 更新时间:2024-10-10 09:15:33
本文介绍了如何在自身中使用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函数?

本文发布于:2023-11-28 04:46:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641007.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   如何在   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!