概述
#include <functional>
#include <iostream>
#define MY_CALLBACK_0(__selector__,__target__,

#define MY_CALLBACK_1(__selector__,__target__,

#define MY_CALLBACK_2(__selector__,__target__,

#define MY_CALLBACK_3(__selector__,__target__,

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();
}
最后
以上就是老实小甜瓜为你收集整理的使用C++11 std::bind和std::function实现回调机制的全部内容,希望文章能够帮你解决使用C++11 std::bind和std::function实现回调机制所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复