Search code examples
c++arduinoarduino-idearduino-esp8266arduino-c++

C++: How to correct to set up reference of the class function into the non-class reference variable


I have been use the MQTT-library by Goel Gaehwiller(ver. 2.5.0) ad got a little problem with the implementation of the MQTTClient into my own class. The library used a non-class function as a call-back. I tried to use many C++ macroses, but all break the compilation:

void CMQTT::local_mqtt_callback(MQTTClient* client, char* topic, char* payload, int payload_length)
{
    //if ( call_back != NULL )
    //    call_back( client, topic, payload, payload_length );
}

void CMQTT::doMQTTSetting()
{
    mqtt_client->begin(host.c_str(), port, *wifiClient);

    //mqtt_client->onMessageAdvanced( std::bind2nd(std::mem_fun(&CMQTT::local_mqtt_callback),1) ); //no matching function for call to 'mem_fun(void (CMQTT::*)(MQTTClient*, char*, char*, int))'
    //mqtt_client->onMessageAdvanced( std::bind2nd(&CMQTT::local_mqtt_callback,1) ); //no matching function for call to 'MQTTClient::onMessageAdvanced(std::binder2nd<void (CMQTT::*)(MQTTClient*, char*, char*, int)>)'
    //mqtt_client->onMessageAdvanced( std::mem_fun(&CMQTT::local_mqtt_callback) );//no matching function for call to 'mem_fun(void (CMQTT::*)(MQTTClient*, char*, char*, int))'
    //mqtt_client->onMessageAdvanced( std::bind(&CMQTT::local_mqtt_callback),this) );//no matching function for call to 'MQTTClient::onMessageAdvanced(std::_Bind_helper<false, void (CMQTT::*)(MQTTClient*, char*, char*, int)>::type, CMQTT*)'

    mqtt_client->onMessageAdvanced(CMQTT::local_mqtt_callback);
    mqtt_client->subscribe(subTopic);
}

What is incorrect in my code? I know, that declaration of function local_mqtt_callback as static would be decission, but I can understand what is wrong in my code.


Solution

  • I guess the callback is a std::function type,

    You can use the below,

    using namespace std::placeholders;  
    mqtt_client->onMessageAdvanced(std::bind(&CMQTT::local_mqtt_callback,this,_1,_2,_3,_4));