gpt4 book ai didi

c++ - 将成员函数作为标准函数回调传递

转载 作者:行者123 更新时间:2023-11-30 01:39:06 24 4
gpt4 key购买 nike

我已经为代码的同一部分苦苦挣扎了几个小时,但我找不到任何可以指导我的答案。

我正在使用一个库,并且一个方法需要将回调作为参数传递。参见 here .

PubSubClient& setCallback(MQTT_CALLBACK_SIGNATURE);

我正在尝试从成员函数中触发此方法,如下所示:

void HouseKeeper::callback(char* topic, uint8_t* payload, unsigned int length) {
// Do something
}

boolean HouseKeeper::connect() {
library.setCallback(callback);
}

编译器给出的错误如下:

no matching function for call to
'PubSubClient::setCallback(<unresolved overloaded function type>)'

note: no known conversion for argument 1 from '<unresolved overloaded function type>' to 'std::function<void(char*, unsigned char*, unsigned int)>'

我对 C++ 很陌生,所以即使是基础知识也离我很远。

最佳答案

成员函数将*this指针作为第一个参数,所以你的函数签名实际上是:

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

虽然库 setCallback 函数中的 std::function 采用:

std::function<void(char*, unsigned char*, unsigned int)>.

您必须在回调的第二个参数中将 uint8_t* 更改为 unsigned char*(感谢 Daniel H),同时摆脱隐含的*this

  • 您可以使用 std::bind 绑定(bind) *this 指针以匹配 setCallback() 签名:

    std::function<void(char*, uint8_t*, unsigned int)> yourFunction = std::bind(&HouseKeeper::callback, this, _1, _2, _3);

    library.setCallback(yourFunction);
  • 或者将您的调用包装在 lambda 函数中:

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

关于c++ - 将成员函数作为标准函数回调传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46489603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com