Using C++11 function & bind

The example of callback in C++11 is shown below.

#include <functional>
void MyFunc1(int val1, int val2)
{
   std::cout <<  __PRETTY_FUNCTION__ << val1 + val2 << std::endl;
}

void MyFunc2(int val1, int val2)
{
   std::cout <<  __PRETTY_FUNCTION__ << val1 + val2 << std::endl;
}


void FunctionBindTest(void)
{
   std::function<void(int)> pb = std::bind(MyFunc1, 10, std::placeholders::_1);
   pb(1);
   pb = std::bind(MyFunc2, 10, std::placeholders::_1);
   pb(2);
}

The output:

void MyFunc1(int, int)11

void MyFunc2(int, int)12

 Another example to show the message handler or can be used for ISR in embedded system design.

class CallbackC
{
private:
   typedef std::function<void(std::string)> funcType;
public:
   /**
    * @brief Constructor
    */
   CallbackC() = default;

   /**
    * @brief Destructor
    */
   ~CallbackC() = default;

   /**
    * @brief Set copy constructor as delete to prevent unintentional creation
    */
   CallbackC(const CallbackC& iValue) = delete;

   /**
    * @brief Set copy assignment as delete to prevent unintentional creation
    */
   const CallbackC& operator=(const CallbackC& iValue) = delete;
   static void RegisterMessage(uint8_t iMsgType, funcType iFunc);
   static void ProcessMessage(uint8_t iMsgType, std::string iMsg);
private:
   static funcType mCallbacks[2];
};

in C++ source file.

CallbackC::funcType CallbackC::mCallbacks[2];

void CallbackC::RegisterMessage(uint8_t iMsgType, funcType iFunc)
{
   mCallbacks[iMsgType] = ifunc;
}

void CallbackC::ProcessMessage(uint8_t iMsgType, std::string iMsg)
{
   mCallbacks[iMsgType](iMsg);
}

class SMSMessageC
{
public:
   void Run(std::string iValue){std::cout <<  __PRETTY_FUNCTION__ << iValue <<std::endl;};
};

class MMSMessageC
{
public:
   void Run(std::string iValue){std::cout <<  __PRETTY_FUNCTION__ << iValue << std::endl;};
};


void CallbackTest(void)
{
   SMSMessageC sms;
   MMSMessageC mms;
   HW::CallbackC::RegisterMessage(0, std::bind(&SMSMessageC::Run, &sms, std::placeholders::_1));
   HW::CallbackC::RegisterMessage(1, std::bind(&MMSMessageC::Run, &mms, std::placeholders::_1));
   HW::CallbackC::ProcessMessage(0, "my message");
   HW::CallbackC::ProcessMessage(1, "my message");
}

The output is:

void SMSMessageC::Run(std::__cxx11::string)my message

void MMSMessageC::Run(std::__cxx11::string)my message

So good! Is it? But the performance is lower than non-member or virtual member function call. The good idea is the SMSMessageC and MMSMessageC are not inherited from a same parent class.

 

posted on 2018-02-09 17:07  荷树栋  阅读(216)  评论(0)    收藏  举报

导航