如果需要,如何使用 Boost 库将具有可变参数数量的处理程序传递给类
How To Pass Handler with Variable Number of Arguments To A Class Using Boost Library If Needed
这个问题已经困扰了我好几天了。 它看起来很简单,但我很难弄清楚。
基本上,我想在以下代码片段中做一些类似于 async_wait 函数的事情
boost::asio::io_services io;
boost::asio::deadline_timer timer(io);
timer.expires_from_now(boost::posix_time::milliseconds(1000));
timer.async_wait(boost::bind(&FunctionName, arg1, arg2, ...)); // How to implement this in my class A
我的示例代码:
#include <iostream>
#include <string>
//#include <boost/*.hpp> // You can use any boost library if needed
// How to implement this class to take a handler with variable number of arguments?
class A
{
public:
A()
{
}
void Do()
{
// How to call the handler with variable number of arguments?
}
};
void FreeFunctionWithoutArgument()
{
std::cout << "FreeFunctionWithoutArgument is called" << std::endl;
}
void FreeFunctionWithOneArgument(int x)
{
std::cout << "FreeFunctionWithOneArgument is called, x = " << x << std::endl;
}
void FreeFunctionWithTwoArguments(int x, std::string s)
{
std::cout << "FreeFunctionWithTwoArguments is called, x = " << x << ", s =" << s << std::endl;
}
int main()
{
A a;
a.Do(); // Will do different jobs depending on which FreeFunction is passed to the class A
}
P.S.:如果需要,您可以使用任何提升库,例如boost::bind,boost::function
class A {
public:
A() {}
typedef boost::function<void()> Handler;
void Do(Handler h) {
h();
}
};
...
A a;
int arg1;
std::string arg2;
a.Do(&FreeFunctionWithNoArguments);
a.Do(boost::bind(&FreeFunctionWithOneArgument, arg1));
a.Do(boost::bind(&FreeFunctionWithTwoArguments, arg1, arg2));
如果您有 C++1x 编译器,请将boost::
替换为 std::
。
相关文章:
- 数数并选择 sqlite 中的前三名
- C++:是否可以编写一个函数,将不同类型的元素附加到变体数组中?
- 通过参考变差函数传递N-D数组
- 数数并说在C++中使用递归
- C++ 通过引用函数传递数组,但内容保持不变
- 具有空构造函数使数组未初始化会使计算速度变慢
- 如何将全局字符变量值分配给数组?
- 我在代码中收到一个运行时错误,该错误如何通过修改最多一个元素来查找数组是否可以变得不减少
- 数独百变需要帮助
- 如何替换QT QML中的变体数组文本
- 字符串的变体数组包含替代空间
- 不同的计数器,同一数组.数组元素不变.C
- 将变参数包中的值加载到临时数组中
- char数组变长会导致意外值
- 排列 +ve 和 -ve 编号的数组,顺序不变
- 如何将小数数组转换为二进制数数组
- 数组元素的值保持不变
- 合并排序变体:使用链接数组
- 传递引用以修改数组之后,为什么它保持不变
- 返回对大小不变的指针数组的引用的最佳方式是什么