簡體   English   中英

如何將 std::bind 與 std::function 一起使用以便將方法作為回調傳遞?

[英]How to use std::bind with std::function in order to pass method as a callback?

我在 SO 上找到了這個答案

https://stackoverflow.com/a/40944576/5709159

我在回答中做了所有事情,但我收到一個錯誤

有我的代碼

我需要傳遞回調的方法

/*static*/ void Utils::copy_files(std::function<void(int, int)> progress_callback,
        std::string const & path_from,
        std::string const & path_to)
    {
....
    }

我的回調實現

void TV_DepthCamAgent::progress_callback(int count, int copied_file)
{
...
}

用法

void TV_DepthCamAgent::foo()
{
...
auto callback = std::bind(&TV_DepthCamAgent::progress_callback,
        this);

    shared::Utils::copy_files(callback, path_from_copy, path_to_copy);
...
}

我得到了一個錯誤

SE0312 不存在從“std::_Binder”到“std::function”的合適的用戶定義轉換

錯誤 C2664“void shared::Utils::copy_files(std::function,const std::string &,const std::string &)”:無法將參數 1 從“std::_Binder”轉換為“std::function” '

我究竟做錯了什么?

你錯過了占位符:

auto callback = std::bind(&TV_DepthCamAgent::progress_callback,
                          this,
                          std::placeholders::_1,
                          std::placeholders::_2);

但更簡單的,IMO,是使用 lambda:

auto callback = [this](int count, int copied_file){
     return this->progress_callback(count, copied_file);
};

暫無
暫無

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

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