Templates
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:
and used it in your program like:
Imagine that the compiler is creating a version of your macro definition for each case it is used in behind the scenes, i.e.:
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;
}
Alright, thank you very much...Lets say i do something like this:
...T would be undeclared. Dont i need to it this way?:
Thanks again...
-René
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;
}
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
Popular Topics
Advertisement
Recommended Tutorials
Advertisement