2017-09-06 19 views
2

我寫一個接受回調FN完成後調用異步函數。一般來說,這工作正常(但有一些限制),我可以發送params如下。的boost ::綁定發送可變數量的回調參數的個數回調函數

#include <boost/bind.hpp> 
#include <iostream> 

void foo_cb(int result, const char* data) { 
    std::cout << "foo_cb executed with params " << result << ", " << data << std::endl; 
} 


//void foo_caller(std::function<void(int, const char*)> ff) { 
//template <typename... Args> 
void foo_caller(std::function<void(int, const char*)> ff) { 
    std::cout << "Caller executing..." << std::endl; 
    ff(1, "hi"); 
} 

int main(int argc, char** argv) { 
    int x = 122; 
    const char* y = "Hello nether world"; 
    foo_caller(boost::bind(foo_cb, x, y)); 
    return 0; 
} 

我這裏有兩個問題:

  1. 內foo_caller()函數,在調用回調FF,我不得不放棄一些虛擬值,以滿足稱爲FN即FF函數簽名(1 ,「嗨」);但是,這會正確執行並打印在main()中傳遞的原始值。它看起來非常不自然,必須用某些值調用ff(),這些值不會被使用。

  2. 在我的main(),我可以決定通過不同類型和/或參數,以被叫回功能號碼,因此我寫了完成處理。在這種情況下,實際上,我怎麼寫異步函數foo_caller(...)採取可變數量的指定參數和數據類型和正確調用完成處理?

更新

感謝Jonesinator,說完看着的std ::佔位符後,我意識到我在做什麼錯誤。

  1. foo_caller簽名n的定義是錯誤的。從主
  2. 調用也是錯誤的。

代碼的更新版本的工作原理是,如下所示:

void foo_cb(int result, const char* data) { 
    std::cout << "foo_cb executed with params " << result << ", " << data << std::endl; 
} 


void foo_caller(std::function<void(int, const char*)> ff, int a, const char* b) { 
    std::cout << "Caller executing..." << std::endl; 
    ff(a, b); 
} 


int main(int argc, char** argv) { 

    int x = 122; 
    const char* y = "Hello nether world"; 
    foo_caller(std::bind(foo_cb, std::placeholders::_1, std::placeholders::_2), x, y); 
    return 0; 
} 

回答

3

由於您使用std::function你應該也使用std::bind。該std::bind功能可以placeholder arguments對於未在創建std::function的時間約束參數。

0

對於您的第一個問題:既然你綁定參數的函數,foo_caller的簽名應該是:

void foo_caller(std::function<void()> ff) 

的boost ::綁定拷貝參數你通過,並創建一個新的可調用實體,可以是沒有參數調用(因爲它們被這個新實體所知)並返回void。

當你想在以後的時間來傳遞參數,你必須綁定佔位符像Jonesinator他回答說。