前言
类模版std::function是一种通用、多态的函数封装。std::function的实例可以对任何可以调用的目标实体进行存储、复制、和调用操作,这些目标实体包括普通函数、Lambda表达式、函数指针、以及其它函数对象等。
这是比较官方的解释,最近在学习std::function的用法,看了一些示例后,记录一些自己的用法和理解。
个人体悟
示例用法
class TUI_task_logic
{
using CallBackFunc = std::function<void()>;
public:
TUI_task_logic(CallBackFunc eventchange_call = nullptr, CallBackFunc enter_newday_call = nullptr);
virtual ~TUI_task_logic();
CallBackFunc m_eventchange_call = nullptr;
CallBackFunc m_enter_newday_call = nullptr;
};
TUI_task_logic::TUI_task_logic(CallBackFunc eventchange_call, CallBackFunc enter_newday_call)
{
if (eventchange_call)
m_eventchange_call = eventchange_call;
if (enter_newday_call)
m_enter_newday_call = enter_newday_call;
}
TUI_task_logic::~TUI_task_logic()
{
}
std::unique_ptr<TUI_task_logic> m_task_logic;
m_task_logic = std::make_unique<TUI_task_logic>(
std::bind(&OtherClass::__NotifyEventRecordChange, this), std::bind(&OtherClass::__EnterNewDay, this));
//多参调用std::bind(&OtherClass::_OtherFunc, this, std::placeholders::_1, std::placeholders::_2));
using CallBackFunc = std::function<void()>;
定义CallBackFunc为void()类型的包装,这里个人理解通俗的讲就是void()类型的函数指针,本质上认为std::function其实就是函数指针。这里也可以为各种类型,比如void(int,const char*)、int(const std::string&)等等,看需求。
m_task_logic = std::make_unique<TUI_task_logic>(std::bind(&OtherClass::__NotifyEventRecordChange, this), std::bind(&OtherClass::__EnterNewDay, this));
这句是建立了一个TUI_task_logic对象,绑定函数是OtherClass::__NotifyEventRecordChange、
OtherClass::__EnterNewDay。
此时在TUI_task_logic中调用m_eventchange_call()、m_enter_newday_call()即可分别调用到两个函数