C ++ boost如何将函数作为参数传递给异步操作处理程序

时间:2014-07-15 13:00:31

标签: c++ boost boost-asio

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

#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

1 个答案:

答案 0 :(得分:2)

它对我有用: Live On Coliru

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

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