Code About Us Tutorial


  Templates
    Template Functions
    Multiple Template Parameters
    Template Specialization
    Class Templates
    Linked List
    Linked List Template
    Binary Tree


   
 

Home > Templates > Multiple Template Parameters

December 1, 2009 1:22 am

   

Multiple Template Parameters

The good thing about templates is that you can also use multiple parameters like this:

 

 
template <class T, class E, class M, Class P>
foo <pattern> (parameters);

Where "pattern" is the typename or class that you are sending in. But since C++ is type-specific, it automatically knows what type you are talking about when you pass in variables. Thus, the pattern is sometimes optional. If the case is that you are sending in a pointer to a type, you will need to use the <pattern>. And when you make the call to the function, you can do so like this:

 

 
foo <int, long, float, double>(15, 20012408, 3.1415926, 84626433832795);

But the use of variables will let the compiler figure out the types and will not require the type pattern. Going back to the template swap function, in the body of the swap function I previously declared a temporary variable (Temp) of type "T". So in this case, everywhere I put the letter T, the type that has been passed into the function replaces it (in this case int). The reason for that is because I passed two integers to the swap function. Here is the code that would do it.

 

 
#include <iostream.h>
#include "temp.h"  			//name of the file I put the template function 

void main() { int x = 5, y = 10; cout <<"Before Swap:n"; cout <<"x: " << x << "n"; cout <<"y: " << y << "nn";

swap(x,y);

cout <<"After Swap.nn"; cout <<"x: " << x << "n"; cout <<"y: " << y << "n"; }

If I would have had passed two strings to the swap function it would replace the T with a string instead of an integer. If you didn’t use a template you would have had to rewrite the whole function to accept all of the different types.Please Rate this Code:


    Comments for: Multiple Template Parameters
Annonymouse User says:
poopheafnk jgj hgb




Add Comment:
Name:
Email:


 «2» THINKQUEST TEAM C0111571 © 2001. All Rights Reserved.