如果需要,如何使用 Boost 库将具有可变参数数量的处理程序传递给类

How To Pass Handler with Variable Number of Arguments To A Class Using Boost Library If Needed

本文关键字:数数 变参 处理 程序 何使用 Boost 如果      更新时间:2023-10-16

这个问题已经困扰了我好几天了。 它看起来很简单,但我很难弄清楚。

基本上,我想在以下代码片段中做一些类似于 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::