开发者

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

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::str开发者_高级运维ing 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


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));

If you have a C++1x compiler, replace boost:: with std::.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜