如果需要,如何使用 Boost 库将具有可变参数数量的处理程序传递给类
这个问题已经困扰我好几天了。看起来很简单,但对我来说却很难弄清楚。
基本上,我想在以下代码片段中执行类似 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
}
PS:如果需要,您可以使用任何 boost 库,例如 boost::bind、boost::function
This question has been haunting me for several days. It looks very simple, but it's very difficult for me to figure it out.
Basically, I want to do something like the async_wait function in the following code snippet
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
My sample code:
#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.: you can use any boost library if needed, such as boost::bind, boost::function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您有 C++1x 编译器,请将
boost::
替换为std::
。If you have a C++1x compiler, replace
boost::
withstd::
.