<p>I wrote a sample program at <a href="http://codepad.org/ko8vVCDF" rel="noreferrer">http://codepad.org/ko8vVCDF</a> that uses a template function.</p>

<p>How do I retrict the template function to only use numbers? (int, double etc.)</p>

<pre><code>#include &lt;vector&gt;
#include &lt;iostream&gt;

using namespace std;

    template &lt;typename T&gt;
T sum(vector&lt;T&gt;&amp; a)
{
    T result = 0;
    int size = a.size();
    for(int i = 0; i &lt; size; i++)
    {
        result += a[i];
    }

    return result;
}

int main()
{
    vector&lt;int&gt; int_values;
    int_values.push_back(2);
    int_values.push_back(3);
    cout &lt;&lt; "Integer: " &lt;&lt; sum(int_values) &lt;&lt; endl;

    vector&lt;double&gt; double_values;
    double_values.push_back(1.5);
    double_values.push_back(2.1);
    cout &lt;&lt; "Double: " &lt;&lt; sum(double_values);

    return 0;
}
</code></pre>

Why would you want to restrict the types in this case? Templates allow "static duck typing", so anything allowed by what your
```
sum
```
function in this case should be allowed. Specifically, the only operation required of
```
T
```
is add-assignment and initialisation by 0, so any type that supports those two operations would work. That's the beauty of templates.
(If you changed your initialiser to
```
T result = T();
```
or the like, then it would work for both numbers and strings, too.)