公告

大中华汽车电子生态圈社区并入开发者社区- 更多资讯点击此

Tip / 登入 to post questions, reply, level up, and achieve exciting badges. Know more

cross mob

XMC实验分享之128: C++函数对象

XMC实验分享之128: C++函数对象

User12775
Level 5
Level 5
First solution authored First like received

C语言中动态绑定常用函数指针, 比如:

/**
rief Access structure of the USART Driver.
*/
typedef struct _ARM_DRIVER_USART {
  ARM_DRIVER_VERSION     (*GetVersion)      (void);                              ///< Pointer to 
ef ARM_USART_GetVersion : Get driver version.
  ARM_USART_CAPABILITIES (*GetCapabilities) (void);                              ///< Pointer to 
ef ARM_USART_GetCapabilities : Get driver capabilities.
  int32_t                (*Initialize)      (ARM_USART_SignalEvent_t cb_event);  ///< Pointer to 
ef ARM_USART_Initialize : Initialize USART Interface.
  int32_t                (*Uninitialize)    (void);                              ///< Pointer to 
ef ARM_USART_Uninitialize : De-initialize USART Interface.
  int32_t                (*PowerControl)    (ARM_POWER_STATE state);             ///< Pointer to 
ef ARM_USART_PowerControl : Control USART Interface Power.
  int32_t                (*Send)            (const void *data, uint32_t num);    ///< Pointer to 
ef ARM_USART_Send : Start sending data to USART transmitter.
  int32_t                (*Receive)         (      void *data, uint32_t num);    ///< Pointer to 
ef ARM_USART_Receive : Start receiving data from USART receiver.
  int32_t                (*Transfer)        (const void *data_out,
                                                   void *data_in,
                                             uint32_t    num);                   ///< Pointer to 
ef ARM_USART_Transfer : Start sending/receiving data to/from USART.
  uint32_t               (*GetTxCount)      (void);                              ///< Pointer to 
ef ARM_USART_GetTxCount : Get transmitted data count.
  uint32_t               (*GetRxCount)      (void);                              ///< Pointer to 
ef ARM_USART_GetRxCount : Get received data count.
  int32_t                (*Control)         (uint32_t control, uint32_t arg);    ///< Pointer to 
ef ARM_USART_Control : Control USART Interface.
  ARM_USART_STATUS       (*GetStatus)       (void);                              ///< Pointer to 
ef ARM_USART_GetStatus : Get USART status.
  int32_t                (*SetModemControl) (ARM_USART_MODEM_CONTROL control);   ///< Pointer to 
ef ARM_USART_SetModemControl : Set USART Modem Control line state.
  ARM_USART_MODEM_STATUS (*GetModemStatus)  (void);                              ///< Pointer to 
ef ARM_USART_GetModemStatus : Get USART Modem Status lines state.
} const ARM_DRIVER_USART;

C++中有更加智能, 更加灵活的方法, std::function就是一种.


简单讲, std::function类似于std::string 、std::vector<> 、这样的类型。只不过其值为函数指针,但比函数指针更灵活。
因为std::function  是一种模板,所以要传入类型,就如std::vector<int>  传入类型int一样
不过,std::function传入的是函数类型  返回值 (参数类型) 如:std::function<void (int)>.

下面通过几个简单例子演示一下其基本用法.

0 点赞
710 次查看
4 评论