C++:如何更正将 class 函数的引用设置为非 class 引用变量

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

我一直在使用 Goel Gaehwiller 的 MQTT-library(ver. 2.5.0)广告,在将 MQTTClient 实施到我自己的 class 中时遇到了一点问题。该库使用非 class 函数作为回调。我尝试使用许多 C++ 宏,但都破坏了编译:

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);
}

我的代码有什么不正确的地方?我知道,将函数 local_mqtt_callback 声明为 static 将是决定性的,但我可以理解我的代码中有什么问题。

你能试试下面的方法吗,

mqtt_client->onMessageAdvanced(&mqtt_client,&CMQTT::local_mqtt_callback);

你也可以用std::function代替

我猜回调是std::function类型,

你可以使用下面的,

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

CMQTT::local_mqtt_callback为非静态时,其第一个参数是CMQTT*类型的隐藏this指针。只有当CMQTT::local_mqtt_callback是static时,它的第一个参数才变成MQTTClient* client。也就是说,如果 CMQTT::local_mqtt_callback 是非静态的,则需要将 this 绑定到第一个参数。