C ++存储指向在编译时可以推断出返回类型的函数的指针

问题描述

我有一个C ++类,该类仅存储通过其构造函数传递的std::string函数指针,在调用getData()时执行该函数指针,然后返回字符串。这意味着我可以创建一个指向该类实例的指针数组,以用于各种用途。

我希望能够传递构造函数 any 函数指针类型,并让getData()返回std::string。对于返回类型具有与类中函数相同类型的显式构造函数和成员变量的函数,传递函数指针可以正常工作。但这意味着我需要为每种可能的类型使用一个指针占位符变量。

我考虑过使用模板化的构造函数,但是由于没有类型可存储的函数类型的变量,因此无法存储函数指针,并且无法模板化成员变量。我可以对整个类进行模板化,但是似乎有点过头了,并且调用构造函数在整个宫殿中都涉及className<type>,而且由于模板类型必须匹配,所以我无法将结果指针存储在数组中。 >

此外,构造函数会过载,因此也可以传入任何非函数类型,并且在运行getData()时,它将被视为静态数据。

代码在ESP32上运行,因此我宁愿避免将内容包装在std::function中以最小化开销。

一些背景知识:该类构成其他类要遵循的非常基本的接口。它是Web服务器的一部分,该服务器在HTML文件中搜索占位符,将它们与“注册”的占位符进行匹配以作为映射中的键,并最终运行值对象的getData()函数。结果将替换占位符。

只要传入的函数返回std::string(),下面的实现就可以工作。为简洁起见,它缺少非功能类型的重载。

感谢您的帮助!

webDataProvider.hpp:

#include <string>

#ifndef WEBDATAPROVIDER_HPP
#define WEBDATAPROVIDER_HPP

class webDataProvider
{

private:
    std::string(*funcPtr)() = NULL;

public:
    webDataProvider(){};

    template <class F>
    webDataProvider(F _funcPtr())
    {
        funcPtr = _funcPtr;
    };

    virtual std::string getData()
    {
        return funcPtr();
    }
};

#endif

main.cpp:

#include <map>
#include <string>

#include "webDataProvider.hpp"

map<std::string,webDataProvider*> globalPlaceholders;


std::string uptime(){
    return std::to_string(esp_timer_get_time());
}

void app_main(){

    globalPlaceholders.emplace("{{uptime}}",new webDataProvider(uptime));

    printf("Placeholder for uptime is %s",globalPlaceholders["{{uptime}}"]->getData().c_str());

}

编辑: 我希望能够做到这一点:

main.cpp

#include <map>
#include <string>

#include "webDataProvider.hpp"

map<std::string,webDataProvider*> globalPlaceholders;


std::string uptime(){
    return std::to_string(esp_timer_get_time());
}

float floatValue(){
    //const value purely for example,this could return a different value each time it runs
    return 678.910;
}

void app_main(){
    //example of a function that uses a wrapper
    globalPlaceholders.emplace("{{uptime}}",new webDataProvider(uptime));

    //but it would be cleaner to do this:
    globalPlaceholders.emplace("{{uptime}}",new webDataProvider(esp_timer_get_time));

    globalPlaceholders.emplace("{{float}}",new webDataProvider(floatValue));
}

很显然,在此示例中,integerValue()可以返回一个字符串,并且我可以创建一个存根包装函数以将我使用的所有函数的返回类型转换为字符串,但这似乎很麻烦。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...