c++ - 使用C++ RTTI(内省(introspection))通过字符串查找函数指针?

标签 c++ rtti

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

关于c++ - 使用C++ RTTI(内省(introspection))通过字符串查找函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55952759/

相关文章:

c++ - 有没有办法在运行时识别变量的 const 修饰符?

delphi - 将泛型类型从一个类传递到另一个类时出错

c++ - 为什么我的 char* 无故改变?

c++ - 重载后/前增量运算符

C++:类的只读和只写版本的语义

java - 为什么 Class.getSuperClass() 方法不能准确获取父类(super class)类型实例?

c++ - IO 完成端口和套接字 WSARecv()

c++ - 当应用于基本类型时,在分配之前检查是否相等是一种过早的悲观化形式吗?

c++ - dynamic_cast 在内部是如何工作的?

德尔福7 : create a new instance of an unknown object