std::function相关用法

文章介绍了std::function在C++中的应用,作为通用的函数封装,它可以存储和调用不同类型的可调用对象,如普通函数、Lambda表达式和函数指针。文中通过TUI_task_logic类展示了如何使用std::function来存储回调函数,以便在类内部进行调用,强调了std::bind的使用来绑定对象方法。
摘要由CSDN通过智能技术生成

前言

类模版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()即可分别调用到两个函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值