c++ - 在 C++ 中动态创建和调用类方法的最简单方法是什么?

标签 c++ model-view-controller object

我想用类名和方法、唯一标识符和指向方法的指针填充映射。

typedef std::map<std::string, std::string, std::string, int> actions_type;
typedef actions_type::iterator actions_iterator;

actions_type actions;
actions.insert(make_pair(class_name, attribute_name, identifier, method_pointer));

//after which I want call the appropriate method in the loop

while (the_app_is_running)
{
    std::string requested_class = get_requested_class();
    std::string requested_method = get_requested_method();

    //determine class
    for(actions_iterator ita = actions.begin(); ita != actions.end(); ++ita)
    {
        if (ita->first == requested_class && ita->second == requested_method)
        {
            //class and method match
            //create a new class instance
            //call method
        }
    }
}

如果方法是静态的,那么一个简单的指针就足够了,问题也很简单, 但我想动态创建对象,所以我需要存储一个指向类的指针和该方法的偏移量,我不知道这是否有效(如果偏移量始终相同等)。

问题是 C++ 缺少反射,在带反射的解释型语言中的等效代码应该如下所示(PHP 中的示例):

$actions = array
(
     "first_identifier" => array("Class1","method1"),
     "second_identifier" => array("Class2","method2"),
     "third_identifier" => array("Class3","method3")
);

while ($the_app_is_running)
{
     $id = get_identifier();

     foreach($actions as $identifier => $action)
     {
         if ($id == $identifier)
         {
             $className = $action[0];
             $methodName = $action[1];

             $object = new $className() ;

             $method = new ReflectionMethod($className , $methodName);
             $method -> invoke($object);    
         }
     }
 }

PS:是的,我正在尝试用 C++ 制作一个(网络)MVC 前端 Controller 。 我知道我知道为什么不使用 PHP、Ruby、Python(在这里插入你最喜欢的网络语言)等?我只想要 C++。

最佳答案

也许您正在寻找 member function pointers .

基本用法:

class MyClass
{
    public:
        void function();
};

void (MyClass:*function_ptr)() = MyClass::function;

MyClass instance;

instance.*function_ptr;

如 C++ FAQ Lite 中所述,宏和 typedef 在使用成员函数指针时会大大提高可读性(因为它们的语法在代码中并不常见)。

关于c++ - 在 C++ 中动态创建和调用类方法的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/405432/

相关文章:

c++ - 我应该考虑网络字节顺序吗?

java - 是否可以使用 Web 框架但不依赖于该框架?

c# MVC - 文件夹结构 - 在哪里放类?

Java:更改对象值而不更改所有引用

javascript - 从json中取出所有数据并显示在index页面

c++ - 这个未知大小数组的列表初始化在 C++0x 中有效吗?

c++ - 为什么需要void_t检查成员类型的存在?

c++ - 诱导编译器避免/触发右值复制

c# - 关于 MVC 中的 SLUG

javascript - 在对象的子数组中搜索 - JavaScript