Click here to Skip to main content
Click here to Skip to main content

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

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

Comments and Discussions

 
GeneralWelcome PinmemberThomas Freudenberg17-Jul-02 23:03 
GeneralRe: Welcome PinsubeditorNishant S17-Jul-02 23:05 
GeneralRe: Welcome PinmemberThomas Freudenberg17-Jul-02 23:12 
GeneralRe: Welcome PinmemberChristian Graus17-Jul-02 23:22 
GeneralRe: Welcome PinmemberThomas Freudenberg17-Jul-02 23:28 
GeneralRe: Welcome PinmemberStefan Spenz17-Jul-02 23:58 
GeneralRe: Welcome PinmemberStefan Spenz17-Jul-02 23:55 
GeneralRe: Welcome PinmemberThomas Freudenberg18-Jul-02 0:01 
GeneralRe: Welcome PinmemberStefan Spenz18-Jul-02 0:04 
GeneralRe: Welcome PinmemberThomas Freudenberg18-Jul-02 0:06 

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.

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