假设我有以下类(class):(可能是元生成的)
class MyClass
{
public:
myMethod();
...
}
这里假设一些事情:
1.) I have the class name from somewhere (let's pretend)
2.) I have the names of the class methods somewhere ( std::map< std::string, std::function> ... perhaps? )
所以...因为我可能直到运行时才知道 myMethod()
的名称,有没有办法使用 std::string
调用它?这是假设我在某处存储了一个类函数的名称。
MyClass example;
std::string funcName{ findMyMethod() };//get std::string name of myMethod
example.someHowRunMyMethodUsing_funcName_();
我知道 C++ 通常不适合类似内省(introspection)的情况,但我想弄清楚这一点。
谢谢!
最佳答案
如果维护 std::string
的 map
-> 成员函数指针
,就可以做到这一点。
std::map<std::string, void (MyClass::*)()> functionMap;
functionMap["myMethod"] = &MyClass::myMethod;
以后
// Get the function name from somewhere.
std::string name = getFunctionName();
// Get the object from somewhere.
MyClass* obj = getObject();
// Check whether there is a function corresponding to the function name.
auto iter = functionMap.find(name);
if ( iter != functionMap.end() )
{
auto fun = iter->second;
(obj->*fun)();
}
else
{
// Deal with missing function.
}
关于c++ - 使用 std::string 调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31332253/