Search code examples
c++arduinoesp8266esp32

C++ pass class method as parameter


I'm working with the ESP32. Currently I am migrating my library from an ESP8266 codebase.

I'm currently doing the following:

m_pubSubClient.setCallback( std::bind(&CL::callbackHandler, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

But it seems like the author of the PubSubClient library has changed the signature.

// old
#define MQTT_CALLBACK_SIGNATURE std::function<void(char*, uint8_t*, unsigned int)> callback
//new 
#define MQTT_CALLBACK_SIGNATURE void (*callback)(char*, uint8_t*, unsigned int)

I can't figure out, how to do that with the new signature.


Solution

  • As plain function pointers can not be bound to member functions, you basically just have three choices left: you can declare CL::callbackHandler as a static member function, make it a free function or use a lambda expression (without closures), like

    m_pubSubClient.setCallback([](char* param1, uint8_t* param2, unsigned int param3) {
        // handling the event
    });