我想知道是否可以使用 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
关于c++ - 使用C++ RTTI(内省(introspection))通过字符串查找函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55952759/