定义一个接受函数作为参数的函数
Define a function that accepts a function 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();
}
消息错误为:
In file included from sketch\RealTime.h:13:0,
from sketch\RealTime.cpp:1:
Config.h:22:52: error: typedef 'mappingFunctionType' is initialized (use decltype instead)
typedef void mappingFunctionType(StaticJsonDocument);
映射函数应该这样调用:
void _loadAppConfig() {
_deserializeJson(WIFI_CONFIG_FILEPATH, []() -> {
// This is a mapping function that maps deserialiyed values to a struct
config.interval = doc["interval"];
});
}
请指教。谢谢!
你真正想要的不是函数的类型,而是函数指针的类型。
所以你的 typedef 应该是这样的:
typedef void (*mappingFunctionPtrType)(StaticJsonDocument);
然后你可以像这样使用它:
void foo(mappingFunctionPtrType func)
{
StaticJsonDocument doc;
func(doc); //call the function through its pointer
}
我正在使用 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();
}
消息错误为:
In file included from sketch\RealTime.h:13:0,
from sketch\RealTime.cpp:1:
Config.h:22:52: error: typedef 'mappingFunctionType' is initialized (use decltype instead)
typedef void mappingFunctionType(StaticJsonDocument);
映射函数应该这样调用:
void _loadAppConfig() {
_deserializeJson(WIFI_CONFIG_FILEPATH, []() -> {
// This is a mapping function that maps deserialiyed values to a struct
config.interval = doc["interval"];
});
}
请指教。谢谢!
你真正想要的不是函数的类型,而是函数指针的类型。
所以你的 typedef 应该是这样的:
typedef void (*mappingFunctionPtrType)(StaticJsonDocument);
然后你可以像这样使用它:
void foo(mappingFunctionPtrType func)
{
StaticJsonDocument doc;
func(doc); //call the function through its pointer
}