Click here to Skip to main content
13,559,650 members
Click here to Skip to main content
Add your own
alternative version


160 bookmarked
Posted 17 Jul 2002

A Beginners guide to Templates - Part 1

, 24 Jul 2002
Rate this:
Please Sign up or sign in to vote.
An article about basic function and class templates


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
	void push(const ElemType& anElement);
	void pop(ElemType& anElement);
	bool wasError() const;
	bool isEmpty() const;
	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...


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
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
ThatsAlok30-Aug-11 0:22
memberThatsAlok30-Aug-11 0:22 
GeneralMy vote of 5 Pin
harsha narayana7-Apr-11 23:06
memberharsha narayana7-Apr-11 23:06 
GeneralMy vote of 5 Pin
taelle16-Jul-10 6:20
membertaelle16-Jul-10 6:20 
GeneralA couple of things Pin
John R. Shaw14-Mar-07 16:51
memberJohn R. Shaw14-Mar-07 16:51 
Generaltemplate &lt; class ElemType &gt; Pin
hackervalley6-Aug-04 22:38
memberhackervalley6-Aug-04 22:38 
GeneralSorry guys... Pin
Stefan Spenz18-Jul-02 23:10
memberStefan Spenz18-Jul-02 23:10 
GeneralRe: Sorry guys... Pin
Nishant S18-Jul-02 23:28
subeditorNishant S18-Jul-02 23:28 
GeneralRe: Sorry guys... Pin
Stefan Spenz19-Jul-02 0:01
memberStefan Spenz19-Jul-02 0:01 
GeneralRe: Sorry guys... Pin
onlinewan1-Aug-07 18:43
memberonlinewan1-Aug-07 18:43 
GeneralWelcome Pin
Thomas Freudenberg17-Jul-02 23:03
memberThomas Freudenberg17-Jul-02 23:03 
GeneralRe: Welcome Pin
Nishant S17-Jul-02 23:05
subeditorNishant S17-Jul-02 23:05 
GeneralRe: Welcome Pin
Thomas Freudenberg17-Jul-02 23:12
memberThomas Freudenberg17-Jul-02 23:12 
GeneralRe: Welcome Pin
Christian Graus17-Jul-02 23:22
memberChristian Graus17-Jul-02 23:22 
GeneralRe: Welcome Pin
Thomas Freudenberg17-Jul-02 23:28
memberThomas Freudenberg17-Jul-02 23:28 
GeneralRe: Welcome Pin
Stefan Spenz17-Jul-02 23:58
memberStefan Spenz17-Jul-02 23:58 
GeneralRe: Welcome Pin
Stefan Spenz17-Jul-02 23:55
memberStefan Spenz17-Jul-02 23:55 
GeneralRe: Welcome Pin
Thomas Freudenberg18-Jul-02 0:01
memberThomas Freudenberg18-Jul-02 0:01 
GeneralRe: Welcome Pin
Stefan Spenz18-Jul-02 0:04
memberStefan Spenz18-Jul-02 0:04 
GeneralRe: Welcome Pin
Thomas Freudenberg18-Jul-02 0:06
memberThomas Freudenberg18-Jul-02 0:06 
GeneralNice article Pin
Daniel Andersson17-Jul-02 22:52
memberDaniel Andersson17-Jul-02 22:52 
GeneralRe: Nice article Pin
Stefan Spenz17-Jul-02 22:59
memberStefan Spenz17-Jul-02 22:59 
GeneralRe: Nice article Pin
toxcct7-May-04 23:39
membertoxcct7-May-04 23:39 
GeneralRe: Nice article Pin
Daniel Andersson9-May-04 22:44
memberDaniel Andersson9-May-04 22:44 
GeneralGood, but... Pin
Christian Graus17-Jul-02 22:52
memberChristian Graus17-Jul-02 22:52 
GeneralRe: Good, but... Pin
Stefan Spenz17-Jul-02 22:55
memberStefan Spenz17-Jul-02 22:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Cookies | Terms of Use | Mobile
Web01 | 2.8.180527.1 | Last Updated 25 Jul 2002
Article Copyright 2002 by Stefan Spenz
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid