Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

c++ - How can I store a boost::bind object as a class member?

I'm writing an application that uses boost::asio. Asio's async_receive (or async_read) is invariably shown using a boost::bind object given for callback:

boost::asio::async_read(socket_,
                        boost::asio::buffer(read_msg_.data(),
                                            chat_message::header_length),
                        boost::bind(&chat_session::handle_read_header,
                                    shared_from_this(),
                                    boost::asio::placeholders::error));

That's perfectly nice, but I'd like not to have to recreate the bind object after each call to the callback. Instead, I'd like to create the object, say, in the constructor of my class, and give it to async_receive.

The problem is, I don't know how to declare that object as a class member. All I know is auto, and it obviously won't work as a class member.

class Whatever
{
public:
    Whatever()
    {
        functor = boost::bind(&Whatever::Callback);
    }
private:
    void Callback()
    {
        boost::asio::async_read(socket_,
                        boost::asio::buffer(read_msg_.data(),
                                            chat_message::header_length),
                        functor);
    }

    ?? functor; // How do I declare this?
    ...
};

Note: This may very well be premature optimization, but I'd still like to know how to declare a bind object without auto.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use boost::function:

class Whatever
{
public:
    Whatever()
    {
        functor = boost::bind(
            &chat_session::handle_read_header,
            shared_from_this(),
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred
        );
        boost::asio::async_read(
            socket_,
            boost::asio::buffer(
               read_msg_.data(),
               chat_message::header_length
            ),
            functor
        );
    }
private:
    boost::function<void(const error_code, const size_t)> functor;
};

... or something like that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...