Anyone have a simple example of what a template is and how it's used?

Printable View

- 11-17-2002NakeerbWhat is a template and how can I use one?
Anyone have a simple example of what a template is and how it's used?

- 11-17-2002Sebastiani
Their just great generic programming tools. :)

Code:

template <typename number>

number add( number a, number b){

return a + b;

}

template <class type>

class List {

//...

};

int main(){

int a = 15, b = 16;

float x = 15.3, y = 16.1;

printf("%i", add(a, b));

printf("%.2f", add(x, y));

List <int> list;

list.push_back(10);

list.push_back(12);

//...etc...

return 0;

}

- 11-17-2002Nakeerb
... wha---?!

- 11-17-2002Nakeerb
...

- 11-17-2002correlcjHope this helps!Quote:

*Originally posted by Nakeerb*

**...**

Hope this helps!

cj

;) - 11-18-2002Nakeerb
I do not understand

- 11-18-2002correlcj...Quote:

*Originally posted by Nakeerb*

**I do not understand**

;) - 11-18-2002Lazy Student
Look at my example below:

PHP Code:`#include <iostream.h>`

template <class T>

T sum (T x, T y){

T result= x + y;

return result;

}

int main()

{

cout<<"The sum of two float numbers, 1.264 and 5.984 is: "<<sum(5.984,1.264)<<endl

<<"The sum of two integers, 5 and 6 is: "<<sum(5,6)<<endl

<<"the sum of two characters, A and B is: "<< sum('A','B')<<endl

<<"the sum of two doubles, 564654646 and 5454873333 is: "<< sum(564654646,5454873333);

system("PAUSE");

return 0;

}

- 11-18-2002...
did someone call me?

- 11-18-2002Stoned_Coder
A few people have tried to show you templates but have done little in explaining them.

When you write a template you are in effect giving your compiler instructions for generating code. You write 1 template function or 1 template class and your compiler will generate as many different versions of these functions as are needed.

Lets look at template functions first.

Imagine a function to return the max of two ints. Something simple like this...

Code:`int max (int num1,int num2)`

{

if (num1>num2) return num1;

else // not necessary but i believe makes code more readable

return num2;

}

Code:`template < typename T >`

const T& max (const T& num1, const T& num2)

{

if (num1 > num2) return num1;

else

return num2;

}

While on the subject of template functions we should talk about explicit specialization. For instance the max of 2 char* strings should use strcmp() and not operator > (). So with this in mind we write a specialized version of max.

Code:`const char* max (const char* str1,const char* str2)`

{

if (strcmp(str1,str2) < 0) return str1;

else

return str2;

}

Sorry dinners ready now. short essay on template classes and specialization and partial specialization may follow after dinner.

If so far you are still failing to understand this then point out exactly what you are not following and we will try to elaborate a bit.