#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();
}