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

Pet*_*Lee 3 c++ boost bind function boost-asio

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

基本上,我想做一些类似于以下代码片段中的 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
Run Code Online (Sandbox Code Playgroud)

我的示例代码:

#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
}
Run Code Online (Sandbox Code Playgroud)

PS:如果需要,您可以使用任何boost库,例如boost::bind、boost::function

Lam*_*eek 5

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));
Run Code Online (Sandbox Code Playgroud)

如果您有 C++1x 编译器,请替换boost::std::.