Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Really, they just work. They use some pretty basic properties of templates, sometimes called static polymorphism. If you're familiar with the term, it is essentially a form of ducktyping. (If it looks like a duck, and it quacks like a duck, it must be a duck)</p> <p>The trick is simple. Here's a very simple example:</p> <pre><code>template &lt;typename T&gt; void say_hello(const T&amp; t) { t.hello(); } </code></pre> <p>The <code>say_hello</code> function doesn't care which type its argument is. It doesn't have to derive from an interface or make any other kind of "promises" about what it is. All that matters is that the type <em>works</em> in this context. All we do with the type is call its <code>hello</code> function. Which means that this code will compile for any type that has a <code>hello</code> member function.</p> <p>The STL algorithms work similarly. Here's a simple implementation of <code>std::for_each</code>:</p> <pre><code>template &lt;typename iter_type, typename func_type&gt; void for_each(iter_type first, iter_type last, func_type f){ for (iter_type cur = first; cur != last; ++cur) { f(*cur); } } </code></pre> <p>This code will compile whenever the template types live up to the requirements placed on them; <code>iter_type</code> must have the pre-increment ++-operator. It must have a copy constructor, and it must have the != operator, and it must have the *-dereference-operator.</p> <p><code>func_type</code> must implement the function-call operator, taking an argument of the same type as you get by dereferencing an object of type <code>iter_type</code>. If I call <code>for_each</code> with types that satisfy these requirements, the code will compile. <code>iter_type</code> can be any type that satisifies these requirements. There is nothing in the code that says "this shall work with vector iterators and list iterators and map iterators". But as long as vector, list or map iterators implement the operators we use, it'll work.</p>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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