Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:</p> <pre><code>template &lt;template&lt;class&gt; class H, class S&gt; void f(const H&lt;S&gt; &amp;value) { } </code></pre> <p>Here, <code>H</code> is a template, but I wanted this function to deal with all specializations of <code>H</code>.</p> <p><strong>NOTE</strong>: I've been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!).</p> <p>I've been trying to think of good examples, and to be honest, most of the time this isn't necessary, but let's contrive an example. Let's pretend that <code>std::vector</code> <em>doesn't</em> have a <code>typedef value_type</code>. </p> <p>So how would you write a function which can create variables of the right type for the vectors elements? This would work.</p> <pre><code>template &lt;template&lt;class, class&gt; class V, class T, class A&gt; void f(V&lt;T, A&gt; &amp;v) { // This can be "typename V&lt;T, A&gt;::value_type", // but we are pretending we don't have it T temp = v.back(); v.pop_back(); // Do some work on temp std::cout &lt;&lt; temp &lt;&lt; std::endl; } </code></pre> <p><strong>NOTE</strong>: we <code>std::vector</code> has two template parameters, type and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won't need to write out the exact type explicitly.</p> <p>which you can use like this:</p> <pre><code>f&lt;std::vector, int&gt;(v); // v is of type std::vector&lt;int&gt; using any allocator </code></pre> <p>or better yet, we can just use:</p> <pre><code>f(v); // everything is deduced, f can deal with a vector of any type! </code></pre> <p><strong>UPDATE</strong>: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing <code>auto</code>. Now the same function can be written as:</p> <pre><code>template &lt;class Cont&gt; void f(Cont &amp;v) { auto temp = v.back(); v.pop_back(); // Do some work on temp std::cout &lt;&lt; temp &lt;&lt; std::endl; } </code></pre> <p>which is how I'd prefer to write this type of code.</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