使用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;
}
就我而言,这种设置和保留函数指针的手动映射的方法是非常高度的。有"自动"方式?
您会开放使用__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
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 按类型与字符串查找对象
- 使用C RTTI(内置)通过字符串查找功能指针
- 关于获取行和字符串查找函数的问题
- 字符串查找方法找不到第一字母
- C++ 字符串.查找()
- 遇到字符串::查找的问题
- 将一个数组作为子字符串查找到另一个数组中
- 字符串查找第一个非的 C++ 问题
- 如何将通配符与字符串::查找一起使用
- 字符串::查找问题 (C++)
- 性能标准::strstr vs. 标准::字符串::查找
- C++字符串::查找崩溃应用程序
- 使用字符串查找单词的正确方法是什么
- 如何在<string>没有 std::string 中介的情况下制作一个支持通过 C 字符串查找的集合?
- 使用C++根据行中的第一个字符串查找行(仅一个)
- Borland字符串::查找bug
- std::map如何通过字符串查找元素
- 字符串查找函数返回奇数
- 如何使用子字符串查找数字行的正确部分