параметр таймера asio разность async_wait лямбда, привязка, указатель на функцию - PullRequest
0 голосов
/ 19 сентября 2018

Когда я использую boost::asio::steady_timer, я нахожу разницу между lambda, bind, function pointer.

#include <iostream>
#include <boost/asio.hpp>

void print() { std::cout << "Hello, world!" << std::endl; }

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

    boost::asio::steady_timer t(io, boost::asio::chrono::seconds(5));
    t.async_wait(&print); // Error
    t.async_wait([]{print();}) // Error
    t.async_wait(std::bind(print)); // Done

    io.run();

    return 0;
}

Я читаю руководство asio, обработчик async_wait требует const boost::system::error_code& error param.Так что если я изменил print на void print(const boost::system::error_code & /*e*/), все было правильно.Но в примере asio timer4/timer.cc && timeouts/server.cc использовался обработчик, создаваемый связыванием без void print(const boost::system::error_code & /*e*/).Когда я перешел на лямбду, компиляция была неправильной.Итак, какая разница в подписи была между bind && lambda.

#include <iostream>
#include <functional>
#include <boost/asio.hpp>
#include <boost/bind.hpp>

class printer
{
public:
    printer(boost::asio::io_context &io)
        : timer_(io, boost::asio::chrono::seconds(1)), count_(0)
    {
        timer_.async_wait(std::bind(&printer::print, this));
    }

    ~printer() { std::cout << "Final count is " << count_ << std::endl; }

    void print()
    {
        if (count_ < 5) {
            std::cout << count_ << std::endl;
            ++count_;

            timer_.expires_at(timer_.expiry() +
                      boost::asio::chrono::seconds(1));
            timer_.async_wait(boost::bind(&printer::print, this));
            // timer_.async_wait([this]{print();}); Error
        }
    }

private:
    boost::asio::steady_timer timer_;
    int count_;
};

int main()
{
    boost::asio::io_context io;
    printer p(io);
    io.run();

    return 0;
}

1 Ответ

0 голосов
/ 19 сентября 2018

«Частичное», сгенерированное std::bind, обнаруживает и игнорирует аргументы, предоставленные точкой вызова и явно не связанные с связанным кодом.

Минималистичный пример ( godbolted ):

#include <functional>
#include <iostream>

void callme(std::function<void(int, float)> arg) {
    arg(42, 4.2);
}

// or like this
// template <typename F> void callme(F&& arg) {
//     arg(42, 4.2);
// }

int main()
{
    auto fn = std::bind([](){std::cout << "hi there" << std::endl; });
    // auto fn = std::bind([](auto&& x){std::cout << "x=" << x << std::endl; }, std::placeholders::_1);  <-- this works too and prints 42
    // auto fn = std::bind([](auto&& x){std::cout << "x=" << x << std::endl; }, std::placeholders::_2);  <-- and works too and prints 4.2

    callme(fn);
    return 0;
}
...