FAQ 25.04 What are the syntax and semantics for a function template?

The syntax of a function template is the keyword template, some template parameters, then something that looks a lot like a function. But semantically a function template is not a function: it is a cookie cutter to create a family of functions.

Consider a function that swaps its two integer arguments. Just as with Array in the preceding example, repeating the code for swap() for swapping float, char, string, and so on, will become tedious. A single function template is the solution.

 template<class T> void swap(T& x, T& y) {   T temp = x;   x = y;   y = temp; } 

Every time swap() appears with a new combination of parameter types, the compiler creates yet another instantiation of the function template. Here is an example.

 #include <string> using namespace std; int main() {   int    i, j;  /*...*/  swap(i,j);  //swap(int&,   int&)   char   a, b;  /*...*/  swap(a,b);  //swap(char&,  char&)   float  c, d;  /*...*/  swap(c,d);  //swap(float&, float&)   string s, t;  /*...*/  swap(s,t);  //swap(string&,string&) } 

As with class templates, a programmer can get the compiler to bypass the function template when creating a template function: the programmer simply needs to manually create a specialized template function.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net