我写一个接受回调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;
}