Passing a member function as standard function callback

前端 未结 2 1323
一生所求
一生所求 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<void(char*, unsigned char*, unsigned int)>.
    

    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<void(char*, uint8_t*, unsigned int)> yourFunction = std::bind(&HouseKeeper::callback, this, _1, _2, _3);
      
      library.setCallback(yourFunction);
      
    • Or wrap your call in lambda function:

      std::function<void(char*, uint8_t*, unsigned int)> yourFunction = [=](char* topic, uint8_t* payload, unsigned int length) {
          this->callback(topic, payload, length);
      }
      
      library.setCallback(yourFunction);
      
    0 讨论(0)
  • 2021-01-25 17:37

    The "classic" way to use callbacks is to declare your callback function static.

    0 讨论(0)
提交回复
热议问题