【问题标题】:How to use lambda to for boost asio async completion handler如何使用 lambda 来提升 asio 异步完成处理程序
【发布时间】:2014-03-11 01:26:16
【问题描述】:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

void print(boost::asio::deadline_timer* t, int* count)
{
    if (*count < 5)
    {
        std::cout << *count << "\n";
        ++(*count);

        t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
        t->async_wait(boost::bind(print, t, count));
    }
}

int main()
{
    boost::asio::io_service io;

    int count = 0;
    boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
//    t.async_wait(boost::bind(print, &t, &count));
    t.async_wait([&]{ // compile error occurred
        print(&t, &count);
    });

    io.run();

    std::cout << "Final count is " << count << "\n";

    return 0;
}

bind 和 lambda exp. 有什么区别?我想语法上没问题,问题是 async_wait 需要一个带有参数“const boost::system::error_code& e”的函数对象。

【问题讨论】:

    标签: c++ boost lambda bind boost-asio


    【解决方案1】:

    我不是很了解asio,但是添加请求的参数可以解决问题。

    t.async_wait([&] ( const boost::system::error_code& ) {
        print(&t, &count);
    });
    

    看起来 Boost.Bind 的一个怪癖或错误允许对从函数指针生成的绑定表达式添加额外的、被忽略的参数。最好不要依赖这个,而是明确地接受和丢弃错误代码。

    【讨论】:

    • 在 boost::bind 中很奇怪,std::bind 工作正常,可以说 boost::bind 或 std::bind 返回一个带有参数“const error_code&”的函数对象吗?但显然 std::bind 与 boost::system::error_code 无关。
    • @met7 他们必须通常忽略任何传递的参数,error_code 或任何其他类型。我很惊讶 std::bind 正在这样做;我稍后会研究它。
    • Boost.Bind 指定“any extra arguments are silently ignored”。它在标准中没有那么明确,但我相信 func.bind.bind 在声明 INVOKE(fn, t1, ..., tN) 必须是 somew1, w2, ..., wN 的有效表达式时允许该行为。
    • @TannerSansbury 但是,Boost“功能”不适用于从仿函数或 PTMF 生成的绑定对象。不,该标准文本并未暗示这一点;传递的值的数量具体是 N 而不是一些 M ≤ N。
    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多