Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: Design, Function template overriding and lack of polymorphism
    text
    copied!<p>Have a base class A, and a derived class B which overrides function template Func:</p> <pre><code>class A { A() {...}; ~A() {}; template &lt;class T&gt; void Func(const String &amp;sInput, T &amp;tResult) {...} }; class B : public A { B() {...} ~B() {}; template &lt;class T&gt; void Func(const String &amp;sInput, T &amp;tResult) {...} }; </code></pre> <p>(Note that Func is non-virtual, given the lack of support in C++ for templated virtual functions.)</p> <p>Now have a mainprog API, class M:</p> <pre><code>class M { M(boost::shared_ptr&lt;A&gt; &amp;pInterfaceInput): pInterface(pInterfaceInput) {} template &lt;class T&gt; Evaluate(const String &amp;sInput, T &amp;tResult) { pInterface-&gt;Func&lt;T&gt;(sInput, tResult); } private: const boost::shared_ptr&lt;A&gt; pInterface; }; </code></pre> <p>I want the function Evaluate here to support calls to functions on base class A or any of its derived classes (such as B). This class was written with polymorphism in mind before I re-designed class A and B to have templated functions.</p> <p>Now the problem here is that if I pass a shared pointer of the base type to the derived type then Func of the base class will be called, not the derived class being pointed to.</p> <p>How do I get around the lack of dynamic polymorphism here? I've considered making class M a class template on the shared pointer type and having a static_cast in the constructor to ensure this type is of the base class type (A) or of a derived class.</p> <p>What's the nicest way to do this? I'd prefer not to modify classes A and B to get around this problem but all suggestions are welcome.</p> <p>Thanks.</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