Advertisement

Templates

Started by October 20, 2000 06:03 PM
2 comments, last by MadZorg 24 years, 3 months ago
Can someone tell me what a template is? I saw this in a post which was on this board some time ago: template void SomeFunction(T* &t) { delete t; t = NULL; } ...or something like this. How can i use that and what can i use it for??? And in general, what can i use a template for? -René
Templates are like typesafe macros. You declare a function or class as a template and it can operate on pretty much any data type. Think of it like this, if you had the following code:


template void TSwap( T& a, T& b )
{
T c( a );
a = b; b = c;
}


and used it in your program like:


CString strFirst, strLast;
TSwap(strFirst, strLast);

int nFirst, nLast;
TSwap(nFirst, nLast);

CItem itmFirst, itmLast;
TSwap(itmFirst, itmLast);


Imagine that the compiler is creating a version of your macro definition for each case it is used in behind the scenes, i.e.:


void TSwap( CString& a, CString& b )
{
CString c( a );
a = b; b = c;
}



void TSwap( int& a, int& b )
{
int c( a );
a = b; b = c;
}



void TSwap( CItem& a, CItem& b )
{
CItem c( a );
a = b; b = c;
}

Advertisement
Alright, thank you very much...Lets say i do something like this:

template void TSwap( T& a, T& b ){T c( a );a = b; b = c;} 


...T would be undeclared. Dont i need to it this way?:

template  TSwap(T &a, T &b ){T c( a );a = b; b = c;} 


Thanks again...

-René


I think part of your problem with template code on the board is that the part of templates that make it run get hidden between <''s and >''s;. Which means that most of the time the stuff in between gets lost in web formatting.

ex:
template < class T > void swap (T &a, T &b) {
T c;
c = a;
a = b;
b = a;
}

This topic is closed to new replies.

Advertisement