Click here to Skip to main content
Licence 
First Posted 17 Jul 2002
Views 198,549
Bookmarked 138 times

A Beginners guide to Templates - Part 1

By | 24 Jul 2002 | Article
An article about basic function and class templates

Introduction

Templates can save you a lot of time when developing large applications, by using shared code for different functions and classes. By definition templates are common functions or classes, which work independent from data types. In this beginner tutorial I handle template functions and templates classes. Imagine you have implemented a class that handles a stack and all it's work, pushing, popping, reading status and so on. This stack class can handle double values. But what if you later need a stack for ints, for Cstrings or whatever in the same program? Without the template mechanism you would have to copy and paste code for each stack class. That's not very effective. But with templates you just define the template function or class with all it's own functions and variables, and declare a new variable that gets all the stuff from the template definition. So let's see how this works.

Function templates

Let's assume we need a function template for searching the minimum value from an array of different types:

template < class ElemType >
ElemType calcmin(ElemType elemField[], int iFieldSize)
{
	int iMin = 0;
	for (int  i=1; i < iFieldSize; ++i)
	{
		if (elemField[i] < elemField[iMin])
			iMin = i;
	}
	return elemField[iMin];
}

This is the template definition. The template expects a data type which is being searched and returned within the function. To use the template with the data types you want to be searched, use the template like this:

void LetsTestTheFunctionTemplate()
{
	int iField[] = {1,2,3,4,5,6};
	double dField[] = {2.5, 2.31, 10.23, 15.2};

	int iSize1 = sizeof(iField) / sizeof (int);
	int i = calcmin(iField, iSize1);
	int iSize2 = sizeof(dField) / sizeof(double);
	double d = calcmin(dField, iSize2);
}

The template min is being used for two different data types, an int[] and a double[], but providing the same functionality for each, searching the minimum value in the array and returning it.

Function templates can also be declared as inline, extern or static. When doing so, it's important to put the fields after the keyword template and it's parameters:

template < class ElemType >
inline ElemType swap(ElemType& a, ElemType& b);

Class templates

Defining a class template is almost similar to defining a function template. Let's catch up the example I used at the beginning, the common stack class to handle different data type's stack. The prototype will be defined as the following:

template < typename ElemType, int iSize=100 >
class Stack
{
public:
	Stack();
	~Stack();
	void push(const ElemType& anElement);
	void pop(ElemType& anElement);
	bool wasError() const;
	bool isEmpty() const;
private:
	ElemType elems[iSize];
	int iTop;
	bool bErrorOccd;
};

The implementation doesn't differ much from a normal class implementation, instead of a little more difficult notation. When a class template is defined, it can be used like a normal class, but you've got to specify the parameters within the < and >, and within the template the class name can be used without parameters. So let's look at the implementation for our stack example:

// include your prototype here or use a #define

template < class ElemType, int iSize >
Stack< ElemType, iSize >::Stack()
: iTop(0), bErrorOccd(false)
{
}

template < class ElemType, int iSize >
Stack< ElemType, iSize >::~Stack()
{
}

template < class ElemType, int iSize >
void Stack< ElemType, iSize >::push(const ElemType& anElement)
{
	bErrorOccd = (iTop == iSize);
	if (!bErrorOccd)
		elems[iTop++] = anElement;
}

template < class ElemType, int iSize >
void Stack< ElemType, iSize >::pop(ElemType& anElement)
{
	bErrorOccd = (iTop == 0);
	if (!bErrorOccd)
		anElement = elems[--iTop];
}

template < class ElemType, int iSize >
bool Stack< ElemType, iSize >::wasError() const
{
	return bErrorOccd;
}

template < class ElemType, int iSize >
bool Stack< ElemType, iSize >::isEmpty() const
{
	return (iTop==0);
}

You can use the class template by declaring a new variable like this:

Stack< int > iTheIntStack;
Stack< double, 30 > dTheDoubleStack;

To be continued...

In Part II I'll handle more advanced template functionality like templates inside a template, using friend definitions in templates and some other stuff...

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Stefan Spenz

Web Developer

Germany Germany

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 PinmemberThatsAlok0:22 30 Aug '11  
GeneralMy vote of 5 Pinmemberharsha narayana23:06 7 Apr '11  
GeneralMy vote of 5 Pinmembertaelle6:20 16 Jul '10  
GeneralA couple of things PinmemberJohn R. Shaw16:51 14 Mar '07  
Generaltemplate < class ElemType > Pinmemberhackervalley22:38 6 Aug '04  
GeneralSorry guys... PinmemberStefan Spenz23:10 18 Jul '02  
GeneralRe: Sorry guys... PinsubeditorNishant S23:28 18 Jul '02  
GeneralRe: Sorry guys... PinmemberStefan Spenz0:01 19 Jul '02  
GeneralRe: Sorry guys... Pinmemberonlinewan18:43 1 Aug '07  
GeneralWelcome PinmemberThomas Freudenberg23:03 17 Jul '02  
GeneralRe: Welcome PinsubeditorNishant S23:05 17 Jul '02  
GeneralRe: Welcome PinmemberThomas Freudenberg23:12 17 Jul '02  
GeneralRe: Welcome PinmemberChristian Graus23:22 17 Jul '02  
GeneralRe: Welcome PinmemberThomas Freudenberg23:28 17 Jul '02  
GeneralRe: Welcome PinmemberStefan Spenz23:58 17 Jul '02  
GeneralRe: Welcome PinmemberStefan Spenz23:55 17 Jul '02  
GeneralRe: Welcome PinmemberThomas Freudenberg0:01 18 Jul '02  
GeneralRe: Welcome PinmemberStefan Spenz0:04 18 Jul '02  
GeneralRe: Welcome PinmemberThomas Freudenberg0:06 18 Jul '02  
GeneralNice article PinmemberDaniel Andersson22:52 17 Jul '02  
GeneralRe: Nice article PinmemberStefan Spenz22:59 17 Jul '02  
GeneralRe: Nice article Pinmembertoxcct23:39 7 May '04  
GeneralRe: Nice article PinmemberDaniel Andersson22:44 9 May '04  
GeneralGood, but... PinmemberChristian Graus22:52 17 Jul '02  
GeneralRe: Good, but... PinmemberStefan Spenz22:55 17 Jul '02  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 25 Jul 2002
Article Copyright 2002 by Stefan Spenz
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid