c++ - 使用 std::string 调用类方法

标签 c++ c++11

假设我有以下类(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::stringmap -> 成员函数指针,就可以做到这一点。

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/

相关文章:

c++ - unique_ptr 如何同时支持 "dot"和 "arrow"调用以及未定义的方法?

c++ - 将 std::tr1::shared_ptr 与 std::function/std::bind 混合会导致较新的 gcc 出现编译器错误

c++ - 如何使用模板推导 std::function 的参数类型?

c++ - 是否可以从字符串创建可变参数元组?

c++ - 是否可以使用 dynamic_cast 进行模板类型检查?

c++ - DirectX 多个 DLL 版本?

c++ - 根据某些标准拆分 std::vector

c++ - 谁能解释当前 C++0x 标准草案的这一段?

c++ - 如何从 g++ 链接到 VS2008 生成的 .libs

c++ - 如何从路径中获取文件名的词干?