Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 定义接受函数作为参数的函数_C++_Arduino - Fatal编程技术网

C++ 定义接受函数作为参数的函数

C++ 定义接受函数作为参数的函数,c++,arduino,C++,Arduino,我正在使用库ArduinoJson,我需要创建一个函数,该函数将在SD卡上打开一个文件,反序列化JSON,然后调用一个映射函数,该函数将反序列化的值映射到一个结构中。我需要一个函数参数是一个映射函数,但不知道如何做到这一点。这不会编译: #include <ArduinoJson.h> // This is an attempt to define a type of function that accepts StaticJsonDocument as a parameter /

我正在使用库ArduinoJson,我需要创建一个函数,该函数将在SD卡上打开一个文件,反序列化JSON,然后调用一个映射函数,该函数将反序列化的值映射到一个结构中。我需要一个函数参数是一个映射函数,但不知道如何做到这一点。这不会编译:

#include <ArduinoJson.h>

// This is an attempt to define a type of function that accepts StaticJsonDocument as a parameter
// and it does not compile here.
typedef void mappingFunctionType(StaticJsonDocument);

class ConfigurationLoader {
  private:
    void _loadConfigFile(String filePath, mappingFunctionType mappingFunction)
    void _loadAppConfig();
}
应按如下方式调用映射函数:

void _loadAppConfig() {
  _deserializeJson(WIFI_CONFIG_FILEPATH, []() -> {
    // This is a mapping function that maps deserialiyed values to a struct
    config.interval = doc["interval"];
  });
}
typedef void (*mappingFunctionPtrType)(StaticJsonDocument);

请告知。谢谢大家!

您真正想要的不是函数的类型,而是函数指针的类型

因此,您的typedef将如下所示:

void _loadAppConfig() {
  _deserializeJson(WIFI_CONFIG_FILEPATH, []() -> {
    // This is a mapping function that maps deserialiyed values to a struct
    config.interval = doc["interval"];
  });
}
typedef void (*mappingFunctionPtrType)(StaticJsonDocument);
然后您可以这样使用它:

void foo(mappingFunctionPtrType func)
{
    StaticJsonDocument doc;
    func(doc); //call the function through its pointer
}

您的typedef不正确。链接的问题有一个语法正确的typedef.for函数指针的例子。同样有用的阅读:谢谢你的回答!星号不应该在开头吗?结尾的星号给出了此错误:在sketch\RealTime.h:13:0中包含的文件中,在sketch\RealTime.cpp:1:Config.h:22:37:error:expected')之前加上“”标记类型定义void(mappingFunctionPtrType)(StaticJsonDocument);如果我在开头移动星号,那么它给出的错误与我的问题相同。但如果我用例如int替换StaticJsonDocument,它就会编译。我使用StaticJsonDocument的方式似乎有问题。啊,是的,开头是*号,很抱歉输入错误。另一个错误则与StaticJsonDocument相关。对于一个简单的类,它可以工作:没错,类StaticJsonDocument需要一个模板参数,例如“StaticJsonDocument”。当我添加模板参数时,它被编译了。我很欣赏编译资源管理器中的示例,谢谢!