Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the simplest way to create and call dynamically a class method in C++?
    primarykey
    data
    text
    <p>I want to fill a map with class name and method, a unique identifier and a pointer to the method.</p> <pre><code>typedef std::map&lt;std::string, std::string, std::string, int&gt; 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-&gt;first == requested_class &amp;&amp; ita-&gt;second == requested_method) { //class and method match //create a new class instance //call method } } } </code></pre> <p>If the method is static then a simple pointer is enough and the problem is simple, but I want to dynamically create the object so I need to store a pointer to class and an offset for the method and I don't know if this works (if the offset is always the same etc).</p> <p>The problem is that C++ lacks reflection, the equivalent code in a interpreted language with reflection should look like this (example in PHP):</p> <pre><code>$actions = array ( "first_identifier" =&gt; array("Class1","method1"), "second_identifier" =&gt; array("Class2","method2"), "third_identifier" =&gt; array("Class3","method3") ); while ($the_app_is_running) { $id = get_identifier(); foreach($actions as $identifier =&gt; $action) { if ($id == $identifier) { $className = $action[0]; $methodName = $action[1]; $object = new $className() ; $method = new ReflectionMethod($className , $methodName); $method -&gt; invoke($object); } } } </code></pre> <p>PS: Yes I'm trying to make a (web) MVC front controller in C++. I know I know why don't use PHP, Ruby, Python (insert your favorite web language here) etc?, I just want C++.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload