Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The easiest way to do it would probably be if you let Component have a virtual method called for example <code>test_method</code>. Then you could pass a pointer to a Component to the constructor of Port and then Port could just call this virtual method:</p> <pre><code>Component* c = new Component(); // Port ctor : Port( Component* component ); Port* p = new Port(c); // Port would then call c-&gt;test_method(); </code></pre> <p>or</p> <pre><code>SubtypeComponent* sc = new SubtypeComponent(); // Port ctor : Port( Component* component ); Port* p = new Port(sc); // Port would then call sc-&gt;test_method(); </code></pre> <p>However if for some reason this doesn't give you enough flexibility there is another way to solve your problem: you need to pass a type instead of the method pointer. This type then holds the method (and an object because you can't call a method without an object). Here is an example of this type (you can also use the std::function if you have C++11 available):</p> <pre><code>class Handler { public: virtual std::vector&lt;std::string&gt; handle (std::vector&lt;std::string&gt; arguments) = 0; }; template &lt;class C&gt; class Method: public Handler { C* object; std::vector&lt;std::string&gt; (C::*method) (std::vector&lt;std::string&gt;); public: Method (C *object, std::vector&lt;std::string&gt;(C::*method)(std::vector&lt;std::string&gt;)) { this-&gt;object = object; this-&gt;method = method; } virtual std::vector&lt;std::string&gt; handle (std::vector&lt;std::string&gt; arguments) { // call the method return (object-&gt;*method) (arguments); } }; </code></pre> <p>Now you modify your Port class constructor to take a pointer to a Handler as an argument. Then you can write:</p> <pre><code>Component* c = new Component(); // Port ctor : Port( Handler* handler ); Port* p = new Port(new Method&lt;Component&gt;(c, &amp;Component::test_method)); </code></pre> <p>and</p> <pre><code>SubtypeComponent* sc = new SubtypeComponent(); // Port ctor : Port( Handler* handler ); Port* p = new Port(new Method&lt;SubtypeComponent&gt;(sc, &amp;SubtypeComponent::test_method2)); </code></pre> <p>Also have a look at these questions:<br> <a href="https://stackoverflow.com/questions/7574430/c-member-function-pointers-in-class-and-subclass">C++ member function pointers in class and subclass</a><br> <a href="https://stackoverflow.com/questions/6307566/method-pointer-casting">Method pointer casting</a></p>
 

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