00:00
00:00
Newgrounds Background Image Theme

markololohands just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

C++: Templates

1,272 Views | 8 Replies
New Topic Respond to this Topic

C++: Templates 2007-08-05 01:07:11


Gay Porn/C++ main

I've noticed that there is no tutorial on arguably C++'s most usefull feature, templates. I thought,
what the hell, I might as well write one.

Templates are a way of making functions and classes type independant. They allow you to write
one general function/class, and lets the compiler determine the specifics, namly the type.
Let's take a theoretical example of when templates can be useful. Adding. Say I need to add two
numbers. The process is always the same, x + y. But you have to define different functions to do the
operation with int and doubles. For instance, say I had a program that needed to add two integers
and two doubles at any given time. There are several solutions. One would be to create two
different functions like so:

double addDoubles(double x, double y){ return x+y; }
int addInts(int x, int y) { return x + y; }

Alternativly, if we could make things more professional using function overloading:

double add(double x, double y){ return x+y; }
int add(int x, int y) { return x + y; }

Here the compiler determines at compile-time, which function will be called. Although this is a
better example, you're still writing the same function two times. This isn't a problem with add, but
with a larger function, it can be tedious. This is where templates come into play. Let me throw the

syntax out there:

template <class T>
T add(T x, T y) { return x + y; }

Here we've created a function that is generic. template is a keyword that specifies that this function
is generic. <class T> is the key here. Think of T as a variable that will hold a type. It's a place holder
for a type. If template is called with integer values, T is replaced with int, if it's called with doubles,
T is replaced by double. In this way, add will work with amy base type. Notice that only one

copy of the function is writen. You can use this function just like any other function:

double resultD = add(3.34, 356.54); //calls double version of add
int resultI = add(2, 45); //calls int version of add

In essence, templates allow the compiler to do all overloading, not you. It makes things a lot easier,
and allows you to write functions that are generic and that will work with any type. Handy, eh?
If I wanted to add another function to add floats, I would have to create yet another overloaded
function called add that takes in float. Then I have 3 functions that are the same! With templates, I
wouldn't need to add anything. I could freely just go: float resultF = add(3.2f, 453.3f);
Another benifit of using templates in C++.

Ok, that's a general overview of template functions. Now i'll go over template classes. Let's use a
Stack class as an example. We want to develop a class that will hold a stack of information. Note,
that a stack will hold information the exact same way for every data type. As in every Stack's pop()
and push() method act the same! Now we could make every method of Stack a template, or the
better solution, make the class a template. Here is an example:
template <class T>
class Stack{

int topOfStack;
T info[100]; //Note, it is of type T, which is a place holder for a type

public:
T push(T value) {
info[topOfStack] = value;
topOfStack++;
}

T pop() {
topOfStack--;
return info[topOfStack];
}

};

Now we can create code like this:

Stack<int> intStack;
Stack<doube> doubleStack;

Notice how I need to specify the type in angle brackets when I define the object. For simplicity,
Stack is very limited and not well coded(no bounds checking), but you get the point. I can now call

the methods of both stacks like so:

intStack.push(34);
doubleStack.push(3.1415);

Again, very handy. One final note: I can replace <class T> with <typename T> to achive the same
results. They are the same in thier usage.

Let me know what you thought of this tutorial.

Cinjection.

Response to C++: Templates 2007-08-05 03:10:45


man, i wish i had had this when i was trying to learn how to do a template class/struct. couldve saved me a few hours and a stupid headache from such a simple mistake (didnt know you had to define the template's type in the initialization process at the time).

At 8/5/07 01:07 AM, Cinjection wrote: Stack<doube> doubleStack;

small typo; should be Stack<double>


BBS Signature

Response to C++: Templates 2007-08-05 03:19:32


Nice job man!

Response to C++: Templates 2007-08-05 09:39:56


At 8/5/07 03:10 AM, authorblues wrote: man, i wish i had had this when i was trying to learn how to do a template class/struct. couldve saved me a few hours and a stupid headache from such a simple mistake (didnt know you had to define the template's type in the initialization process at the time).

Thanks :)

At 8/5/07 01:07 AM, Cinjection wrote: Stack<doube> doubleStack;
small typo; should be Stack<double>

Thanks for the corrections.

I should add, if you want to declare a member method outside the header definition(ie, non-inline methods), you can use this as an example:
template <class T>
class Stack{

int tos; //Top Of Stack.
T info[100]; //Create an array to hold everything

public:
void push(T val);
T pop();

};

template <class T>
void Stack<T>::push(int val){

info[tos] = val;
tos++;

}

template <class T>
T Stack<T>::pop(){

tos--;
return info[tos];

}

Note how the full class name is now Stack<T>, rather than Stack. If I were to create an int stack, it's type would be Stack<int>. For a double stack, the official type would be Stack<double>.

Response to C++: Templates 2007-08-05 19:54:29


templates are a pain in my balls because you have to fully define them at the point of declaration, unless you use lame microsoft-specific syntax to 'forward-declare' a templated class.

good post, and decent tutorial but the clincher still remains: you probably wont use templates. if you need a generic stack, STL has a good one. the one time i have personally found a real use for templates is when performing image processing at work; the code needed to work for both 8-bit and 16-bit values in a linear array, and adding if() checks to handle the types in the middle of a 3rd embedded for() loop just wasnt ftw.

so in short, and not to be a total ass, templates are very powerful. in my experience they usually arent necessary, but sometimes they fit the bill and they generalize things very effeciently.


bet you can't end-task this shit without a cold-boot bro

cmd /k echo -^|->-.bat&-

Response to C++: Templates 2007-08-05 22:51:51


I have to admit that I was surprised by the quality of this tutorial. It easily outshines many that I've seen here on Newgrounds.

However, I very much don't like your implementation of the stack, even though I'm sure you were just simplifying it for simplicity's sake. The thing is, you really don't want to use an array (or a vector) to implement a stack, but a linked list.

Here is the stack class that I use:

template <class T> class Stack{
public:
---bool IsEmpty() const {return container.IsEmpty();}
---void Push(const T& item){container.AddFirst(item);}
---void Pop() {container.RemoveFirst();}
---const T& Top() const {return container.ShowFirst();}
private:
---SList<T> container;
}

This is easily readable and you don't necessarily have to understand how the SList (singly-linked list) works in order to understand how the stack works. Since this is a tutorial on templating, this is sufficient; you would want to make a different tutorial explaining how to implement the linked list.

Now for the reasons that a linked list is better than a vector, and especially better than a static array:
1-A static array is ill-suited for a stack because it holds some constant amount of data that can never change. This wastes memory if you don't use that much, and causes a flood of errors if you add to many things. It limits the size of the stack if you add bounds checking, so it's not scalable enough to be used everywhere.
2-A vector is ill-suited for a stack because of the way that it must be dynamically changed every time you want to add a new value, or else it has the same problem as the array, simply wasting memory. I like how you added to the end of the array instead of the beginning (that would have been a royal pain), but this would still be inefficient with a vector, even though it would be dynamically sized.
3-A list is perfectly suited as the data structure for a stack because it only ever has as much data as is needed, and automatically handles the adding and deleting for you. There is no wasted memory and it can store an infinite number of items (well, until you run out of memory).

Great tutorial, and if you ever re-do it, I'd hope you used a list instead of an array. I know it's a tutorial on templates, and that's why you don't go into the implementation of the list.

Response to C++: Templates 2007-08-05 23:25:05


At 8/5/07 10:51 PM, StrixVariaXIX wrote: I have to admit that I was surprised by the quality of this tutorial. It easily outshines many that I've seen here on Newgrounds.

Why thank you!

However, I very much don't like your implementation of the stack, even though I'm sure you were just simplifying it for simplicity's sake. The thing is, you really don't want to use an array (or a vector) to implement a stack, but a linked list.

I agree. I just didn't want to introduce linked lists because that would limit the user base. Anyone who is unfamiliar with lists would be turned off. In reality, a list would be a great data structure for a stack. Following this theme, here is my generic stack class, that of course, uses lists. By the way, the linked list in the above link is my first. Could you point out anything that I might be doing wrong in my implementation? Thanks.

Thanks for the feedback :)

Response to C++: Templates 2007-08-06 00:32:34


I don't have the time to look over it right now, but I will post the SList class that the Stack class I posted uses, so you can compare if you want. I'll look at your class later and see if I can find anything that you might improve.

http://pastebin.com/f469f0701

Response to C++: Templates 2007-08-06 00:50:41


At 8/6/07 12:32 AM, StrixVariaXIX wrote: I don't have the time to look over it right now, but I will post the SList class that the Stack class I posted uses, so you can compare if you want. I'll look at your class later and see if I can find anything that you might improve.

http://pastebin.com/f469f07

Thanks a lot!