Passing a member function as standard function callback

前端 未结 2 1326
一生所求
一生所求 2021-01-25 17:04

I\'ve been struggling for hours with the same part of the code, and I cannot find any answer that can guide me.

I\'m using a library, and a method requires to pass a cal

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-25 17:14

    Member functions take *this pointer as a first parameter, so your function signature is actually:

    void(HouseKeeper*, char*, uint8_t*, unsigned int)
    

    While std::function in library setCallback function takes:

    std::function.
    

    You have to change your uint8_t* to unsigned char* in your callback second parameter (thanks Daniel H), and also get rid of implicit *this.

    • You can use std::bind to bind *this pointer to match setCallback() signature:

      std::function yourFunction = std::bind(&HouseKeeper::callback, this, _1, _2, _3);
      
      library.setCallback(yourFunction);
      
    • Or wrap your call in lambda function:

      std::function yourFunction = [=](char* topic, uint8_t* payload, unsigned int length) {
          this->callback(topic, payload, length);
      }
      
      library.setCallback(yourFunction);
      

提交回复
热议问题