牵着老婆满街逛

严以律己,宽以待人. 三思而后行.
GMail/GTalk: yanglinbo#google.com;
MSN/Email: tx7do#yahoo.com.cn;
QQ: 3 0 3 3 9 6 9 2 0 .

使用C++11 std::bind和std::function实现回调机制


#include <functional>
#include <iostream>


#define MY_CALLBACK_0(__selector__,__target__, ) std::bind(&__selector__,__target__, ##__VA_ARGS__)
#define MY_CALLBACK_1(__selector__,__target__, ) std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__)
#define MY_CALLBACK_2(__selector__,__target__, ) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__)
#define MY_CALLBACK_3(__selector__,__target__, ) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, ##__VA_ARGS__)


typedef std::function<void()> CALLBACK_FUNC;

class Sender
{
public:
    Sender() { callback = nullptr; }
    virtual ~Sender() {}

public:
    void emit()
    {
        std::cout << "I am A,I send a message." << std::endl;
        if (callback) callback();
    }

    void setTarget(CALLBACK_FUNC target)
    {
        callback = target;
    }

public:
    CALLBACK_FUNC callback;
};

struct foo
{
    void doSomething_MemberFunction() const
    {
        std::cout << "I am member function,I got a message!" << std::endl;
    }

    static void doSomething_StaticMemberFunction(int i)
    {
        std::cout << "I am static member function,I got a message! i=" << i << std::endl;
    }
};

void doSomething_GlobalFunction()
{
    std::cout << "I am global function,I got a message!" << std::endl;
}

class Functor
{
public:
    void operator()()
    {
        std::cout << "I am a functor!" << std::endl;
    }
};

void testBindFunction()
{
    Sender sender;
    foo f;

    // 成员函数
    sender.setTarget(std::bind(&foo::doSomething_MemberFunction, &f));
    //sender.setTarget(MY_CALLBACK_0(foo::doSomething_MemberFunction, &f));
    sender.emit();

    // 全局函数
    sender.setTarget(doSomething_GlobalFunction);
    sender.emit();

    // 静态成员函数
    sender.setTarget(std::bind(foo::doSomething_StaticMemberFunction, 666));
    sender.emit();

    // Lambda表达式
    auto lambda = []() { std::cout << "I am Lambda!" << std::endl; };
    sender.setTarget(lambda);
    sender.emit();

    // 仿函数
    sender.setTarget(Functor());
    sender.emit();
}

posted on 2016-10-12 12:12 杨粼波 阅读(1641) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理