我寫一個接受回調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;
}
我這裏有兩個問題:
內foo_caller()函數,在調用回調FF,我不得不放棄一些虛擬值,以滿足稱爲FN即FF函數簽名(1 ,「嗨」);但是,這會正確執行並打印在main()中傳遞的原始值。它看起來非常不自然,必須用某些值調用ff(),這些值不會被使用。
在我的main(),我可以決定通過不同類型和/或參數,以被叫回功能號碼,因此我寫了完成處理。在這種情況下,實際上,我怎麼寫異步函數foo_caller(...)採取可變數量的指定參數和數據類型和正確調用完成處理?
更新
感謝Jonesinator,說完看着的std ::佔位符後,我意識到我在做什麼錯誤。
- foo_caller簽名n的定義是錯誤的。從主
- 調用也是錯誤的。
代碼的更新版本的工作原理是,如下所示:
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;
}