Templates with Multiple Parameters

Written by Raza on. Posted in C++

We have learnt that Templates in C are a very powerful feature. They constitute the concept of Generic Programming or Type Independent Programming. Last time, we saw templates that have one parameter or one generic type. They have the limitation that only one type of data type can be processed at a time. To solve that problem, we use templates with more than one type of parameters. Such multiple type templates allow more than one type of data types to be process at once. 

Our usual declaration of a template function involves writing the template syntax with its generic parameter just above the function which we want to templatise like this.

</p>
<p>template &lt;typename T&gt;</p>
<p>

In this type of template function, we can write as many arguments into the angular brackets as we want. Again, giving them names depends upon us. Last time, I used Another option for those looking to be cured of their body’s opiate addiction within say, a weekend and be back to work on Monday morning is something called the rapid Detoxifying Mouthwash by Stinger method. the name myType for the generic. Although it is perfectly well to do so, the name used widely for the template type across the programming community is T. so I shall use T or similar ones from now on. Here is how we declare a template function with multiple parameters.

</p>
<p>template &lt;typename T, typename S&gt;</p>
<p>T addition (T a, S b)</p>
<p>{</p>
<p>return a b ;</p>
<p>}</p>
<p>&nbsp;</p>
<p>int main ()</p>
<p>{</p>
<p>int a = 2 ;</p>
<p>float b = 2.5 ;</p>
<p>cout &lt;&lt; addition (a, b) ;</p>
<p>return 0 ;</p>
<p>}</p>
<p>

Now observe one thing. The ‘T’ type parameter in this case is integer as we pass an integer 2 to it. The ‘S’ type parameter is float as we pass it 2.5 to it. We are returning the sum of both the numbers from the addition function. In this case, because we return the sum of ‘T’ type, both the numbers would be added according to integer addition. So the answer would be converted into an integer automatically. If we return the sum of ‘S’ type, the returning sum would be of float type as the floating point addition would be performed on them. You would be a bit confused by this but believe me, try this out and you’ll find me right. This is in fact happening because of type casting which I haven’t explained yet. But I surely will, not to worry. Next time I would explain to you class templates. Until that, Good Bye!

Tags: , , ,