Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing object of a template class as a function parameter which expects base template class
    primarykey
    data
    text
    <p>I have a template class which parametrized by another class with deep hierarchy. I want to pass to a function base template class parametrized by another base class. Here is the example: </p> <pre><code>// Base template class test #include &lt;stdio.h&gt; // Base classes template&lt;class T&gt; class Method { public: Method&lt;T&gt; (T * t) { this-&gt;t = t; } virtual int solve() = 0; protected: T * t; }; class Abstract { public: virtual int get() = 0; virtual void set(int a) = 0; }; // Concrete classes, there might be a few of them template&lt;class T&gt; class MethodImpl : public Method&lt;T&gt; { public: MethodImpl&lt;T&gt; (T * t) : Method&lt;T&gt;(t) {} int solve() { return this-&gt;t-&gt;get() + 1; } }; class Concrete : public Abstract { public: int get() { return this-&gt;a; } void set(int a) { this-&gt;a = a; } protected: int a; }; // Uses methods of Base classes only class User { public: int do_stuff(Abstract &amp; a, Method&lt;Abstract&gt; &amp; ma) { a.set(2); return ma.solve(); } }; // Example usage int main () { Concrete * c = new Concrete(); MethodImpl&lt;Concrete&gt; * mc = new MethodImpl&lt;Concrete&gt;(c); User * u = new User(); int result = u-&gt;do_stuff(*c, *mc); printf("%i", result); return 0; } </code></pre> <p>I get this error during compilation:</p> <pre><code>btc.cpp: In function 'int main()': btc.cpp:62: error: no matching function for call to 'User::do_stuff(Concrete&amp;, MethodImpl&lt;Concrete&gt;&amp;)' btc.cpp:50: note: candidates are: int User::do_stuff(Abstract&amp;, Method&lt;Abstract&gt;&amp;) </code></pre> <p>However it works fine if I create local variables with the same logic:</p> <pre><code>int main () { Abstract * a = new Concrete(); Method&lt;Abstract&gt; * ma = new MethodImpl&lt;Abstract&gt;(a); a-&gt;set(2); int result = ma-&gt;solve(); printf("%i", result); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    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