Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat are some other languages that support "partial specialization"?
    text
    copied!<p>Partial template specialization is one of the most important concepts for generic programming in C++. For example: to implement a generic swap function:</p> <pre><code>template &lt;typename T&gt; void swap(T &amp;x, T &amp;y) { const T tmp = x; y = x; x = tmp; } </code></pre> <p>To specialize it for a vector to support O(1) swap:</p> <pre><code>template &lt;typename T, class Alloc&gt; void swap(vector&lt;T, Alloc&gt; &amp;x, vector&lt;T, Alloc&gt; &amp;y) { x.swap(y); } </code></pre> <p>So you can always get optimal performance when you call swap(x, y) in a generic function;</p> <p>Much appreciated, if you can post the equivalent (or the canonical example of partial specialization of the language if the language doesn't support the swap concept) in alternative languages.</p> <p><strong>EDIT</strong>: so it looks like many people who answered/commented really don't known what partial specialization is, and that the generic swap example seems to get in the way of understanding by some people. A more general example would be:</p> <pre><code>template &lt;typename T&gt; void foo(T x) { generic_foo(x); } </code></pre> <p>A partial specialization would be:</p> <pre><code>template &lt;typename T&gt; void foo(vector&lt;T&gt; x) { partially_specialized_algo_for_vector(x); } </code></pre> <p>A complete specialization would be:</p> <pre><code>void foo(vector&lt;bool&gt; bitmap) { special_algo_for_bitmap(bitmap); } </code></pre> <p>Why this is important? because you can call foo(anything) in a generic function:</p> <pre><code>template &lt;typename T&gt; void bar(T x) { // stuff... foo(x); // more stuff... } </code></pre> <p>and get the most appropriate implementation at compile time. This is one way for C++ to achieve abstraction w/ minimal performance penalty.</p> <p>Hope it helps clearing up the concept of "partial specialization". In a way, this is how C++ do type pattern matching without needing the explicit pattern matching syntax (say the match keyword in Ocaml/F#), which sometimes gets in the way for generic programming. </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