使用C RTTI(内置)通过字符串查找功能指针

Using C++ RTTI (introspection) to lookup function pointers by string?

本文关键字:字符串 查找 功能 指针 RTTI 内置 使用      更新时间:2023-10-16

我想知道是否可以使用rtti使用静态方法/函数指针,使用其名称(传递为字符串(

到目前为止,我有以下代码:

#include <map>
int Foo() {
  return 42;
}
int Bar() {
  return 117;
}
typedef int (*function_ptr)();
int main() {
  std::map<std::string, function_ptr> fctmap;
  fctmap["Foo"] = Foo;
  fctmap["Bar"] = Bar;
}

就我而言,这种设置和保留函数指针的手动映射的方法是非常高度的。有"自动"方式?

您会开放使用__PRETTY_FUNCTION__吗?如果是这样,您可以通过解析__PRETTY_FUNCTION__字符串来获取功能的名称。

然后,您可以具有将功能指针插入地图中的辅助功能。

#include <iostream>
#include <map>
#include <string>
using Map = std::map<std::string, int(*)()>;
//-------------------------------------//
template<int(*)()>
struct Get
{
    static constexpr std::string name()
    {
        std::string tmp = __PRETTY_FUNCTION__;
        auto s = tmp.find("= ");
        auto e = tmp.find("; ");
        return std::string(tmp.substr(s+2, e-s-2));
    }
};
template<int(*func)()>
void insert2map(Map &fctmap_)
{
    fctmap_[Get<func>::name()] = func;
}
//-------------------------------------//
int Foo()
{
    return 42;
}
int Bar()
{
    return 117;
}
int VeryVeryLongName()
{
    return 101;
}
//-------------------------------------//
int main()
{
    Map fctmap;
    insert2map<Foo>(fctmap);
    insert2map<Bar>(fctmap);
    insert2map<VeryVeryLongName>(fctmap);
    for (auto &&i : fctmap)
        std::cout<< i.first <<" -> "<<i.second() <<std::endl;
}

在这种情况下,它似乎很好。结果是:

Bar -> 117
Foo -> 42
VeryVeryLongName -> 101

在线示例:https://rextester.com/ohzk79342