【问题标题】:Set callback function of the PubSubClient API in class在类中设置 PubSubClient API 的回调函数
【发布时间】:2019-10-04 09:01:44
【问题描述】:

我想在类构造函数中调用setCallback() 函数,并使用私有方法作为参数。由于函数所需的函数签名,这不起作用。我的函数问题是我无法访问我的类的特定对象的私有字段。

我已经尝试在类文件中创建一个由于静态上下文而无法工作的简单函数。我还尝试传递一个由于签名而不起作用的方法。

#include <PubSubClient.h>

class Test
{
private:
    void callback(char *topic, uint8_t *payload, unsigned int)
    {
        // things
    }

public:
    Test(PubSubClient psc)
    {
        psc.setCallback(callback);
    }
};

出现以下编译错误。

no suitable constructor exists to convert from "void (char *topic, uint8_t *payload, unsigned int)" to "std::function<void (char *, uint8_t *, unsigned int)>"

【问题讨论】:

    标签: c++ arduino mqtt


    【解决方案1】:

    我不熟悉 arduino 编程,所以我的回答假设您指的是 this 类。另外,我不知道您的示例是否故意使用 PubSubClient 的值构造?据我所知,它应该是一个引用或指针,例如

    Test(PubSubClient& psc)
    {
        psc.setCallback(callback);
    }
    

    错误消息很好地解释了问题所在。 setCallback() 方法需要一个 std::function 并且它不能从类成员函数的值中创建一个。 example section of std::function cppreference 为您提供了多种不同的方法来制作 std::function。如果您确定您的 Test 对象与 PubSubClient 一样长,那么我建议您使用 std::bind 示例,例如

    Test(PubSubClient& psc)
    {
        using std::placeholders::_1;
        using std::placeholders::_2;
        using std::placeholders::_3;
        psc.setCallback(std::bind( &Test::callback, this, _1,_2,_3));
    }
    

    【讨论】:

    • 好的,非常感谢。只是为了批准我自己:占位符只是为回调 method 需要的参数(char *topic, uint8_t *payload, unsigned int)保留位置?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    相关资源
    最近更新 更多