函数作为参数传递给异步操作处理程序

函数作为参数传递给异步操作处理程序

主要目标是将我自己的函数作为参数传递给异步操作处理程序。代码如下:

#ifndef TESTCLASS_HPP_
#define TESTCLASS_HPP_
#include "boost/asio.hpp"
#include <boost/function.hpp>
#include <boost/bind.hpp>

class TestClass : public boost::asio::ip::tcp::socket{
public:
    TestClass(boost::asio::io_service& ios) : boost::asio::ip::tcp::socket(ios) {
    }
    virtual ~TestClass() {};

    template <typename ConnectHandler>
    void async_connect(const endpoint_type& peer_endpoint, ConnectHandler handler) {

            boost::asio::ip::tcp::socket::async_connect(peer_endpoint,
                    boost::bind(&TestClass::handle_connect, this, boost::asio::placeholders::error, boost::bind(&TestClass::foo, this)));
    }
private:
    void handle_connect(const boost::system::error_code& err, boost::function<void (void)> func) {
        std::cout<<"handle_connect started"<<std::endl;
        func();
    }

    void foo(){
        std::cout<<"foo started" << std::endl;
    }

};

#endif /* TESTCLASS_HPP_ */

在编译时,我面临以下错误:
boost::asio::ip::basic_endpoint<boost::asio::ip::tcp>]’
    ../main.cc:188:4:   required from here
    /usr/include/boost/bind/bind.hpp:392:9: error: invalid use of void expression
    make: *** [main.o] Error 1

最佳答案

它对我有用: Live On Coliru

但是,通常,请使用boost::protect避免在嵌套绑定(bind)表达式中混淆占位符:

 #include <boost/bind/protect.hpp>



    boost::asio::ip::tcp::socket::async_connect(peer_endpoint,
            boost::bind(&TestClass::handle_connect, this,
                boost::asio::placeholders::error,
                boost::protect(boost::bind(&TestClass::foo, this))));

07-28 01:32