使用std :: string调用classes方法

dav*_*ler 5 c++ c++11

假设我有以下类:(可能是元生成的)

class MyClass
{
    public:
        myMethod(); 
    ...
}
Run Code Online (Sandbox Code Playgroud)

假设这里有一些事情:

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? )
Run Code Online (Sandbox Code Playgroud)

所以...因为我可能不知道myMethod()运行时的名称,有没有办法用它来调用它std::string?这假设我有一个存储在某处的类函数的名称.

MyClass example;

std::string funcName{ findMyMethod() };//get std::string name of myMethod

example.someHowRunMyMethodUsing_funcName_();
Run Code Online (Sandbox Code Playgroud)

我知道C++通常不适合类似内省的情况,但我想弄明白这一点.

谢谢!

Che*_*Alf 3

有很多方法,但使用成员函数指针映射可能是具有相同签名的方法中最通用的方法之一。

#include <iostream>
#include <map>
#include <string>
using namespace std;

class My_class
{
public:
    void method_1() { wcout << "method_1\n"; }
    void method_2() { wcout << "method_2\n"; }
    void method_3() { wcout << "method_3\n"; }
};

auto method_name() -> string { return "method_3"; }

auto main() -> int
{
    map<string, void (My_class::*)()> methods =
    {
        { "method_1", &My_class::method_1 },
        { "method_2", &My_class::method_2 },
        { "method_3", &My_class::method_3 },
    };

    My_class example;
    (example.*methods.at( method_name() ))();
}
Run Code Online (Sandbox Code Playgroud)

支持不同的签名要困难得多。

然后你基本上就会开始 DIY 运行时类型检查。