使用 C++ RTTI(自省)按字符串查找函数指针?

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

我想知道是否可以使用 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;
}

就我而言,这种设置和保持函数指针手动映射的方法非常不优雅。有 "automatic" 方法吗?

您愿意使用 __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