簡體   English   中英

如何將boost :: bind對象存儲為類成員?

[英]How can I store a boost::bind object as a class member?

我正在編寫一個使用boost::asio的應用程序。 Asio的async_receive (或async_read )總是使用為回調提供的boost::bind對象來顯示:

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

這非常好,但我不想在每次調用回調后重新創建綁定對象。 相反,我想在我的類的構造函數中創建對象,並將其賦予async_receive。

問題是,我不知道如何將該對象聲明為類成員。 我所知道的只是汽車,它顯然不會作為班級成員。

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?
    ...
};

注意:這可能是過早優化,但我仍然想知道如何在沒有auto的情況下聲明綁定對象。

使用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;
};

... 或類似的東西。

我想你正在尋找助推功能
只要簽名正確,您就可以將綁定表達式的結果分配給boost :: function對象。

執行此操作的“標准”方法是使functor成為std::function

如果你真的想存儲實際的binder對象,那么查看涉及binder的編譯錯誤消息以找出確切的類型,並嘗試使用它們來確定binder對象的實際類型。

boost :: bind的返回類型是boost :: function 這是一個使用非常簡單的函數的簡單示例:

double f(int i, double d) { 
    cout << "int = " << i << endl; 
    return d; 
} 

boost::function<double (int)> bound_func = boost::bind(f, _1, 1.234); 
int i = 99; 
cout << bound_func(i) << endl;

在您的情況下,該函數具有以下類型:

boost::function<void(const error_code, const size_t)> f;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM