Archived

This topic is now archived and is closed to further replies.

johnnyBravo

c++, what are templates?????

Recommended Posts

Templates are C++'s method to parameterized code at compile time, generally through the use of type parameters. The basic gist is I can define a class or function that I might want to use with different types and only want to write once. In that case I can template that code based on that type. For example, the swap function for integers looks like:

void swap(int & x, int & y) {
int temp = x;
x = y;
y = temp;
}

If I want to use swap with any type, I can do:

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

Then I can use it like:

swap<int>(int_x, int_y);
swap<float>(float_x, float_y);

You might want to consult this section in the C++ FAQ lite or a good recent C++ reference book.

edit: spelling

[edited by - SiCrane on April 6, 2004 7:04:30 AM]

Share this post


Link to post
Share on other sites