Click here to Skip to main content
15,867,308 members
Articles / Mobile Apps

A Beginners Guide to Templates - Part 1

Rate me:
Please Sign up or sign in to vote.
4.50/5 (39 votes)
24 Jul 20022 min read 253.2K   161   50
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 its 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 its 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:

C++
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:

C++
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 its parameters:

C++
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:

C++
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:

C++
// 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:

C++
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.


Written By
Web Developer
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Good, but... Pin
Christian Graus17-Jul-02 23:02
protectorChristian Graus17-Jul-02 23:02 
GeneralRe: Good, but... Pin
Nish Nishant17-Jul-02 23:04
sitebuilderNish Nishant17-Jul-02 23:04 
GeneralRe: Good, but... Pin
Christian Graus17-Jul-02 23:10
protectorChristian Graus17-Jul-02 23:10 
GeneralRe: Good, but... Pin
Thomas Freudenberg17-Jul-02 23:14
Thomas Freudenberg17-Jul-02 23:14 
GeneralRe: Good, but... Pin
Christian Graus17-Jul-02 23:18
protectorChristian Graus17-Jul-02 23:18 
GeneralRe: Good, but... Pin
Thomas Freudenberg17-Jul-02 23:21
Thomas Freudenberg17-Jul-02 23:21 
GeneralRe: Good, but... Pin
Christian Graus17-Jul-02 23:25
protectorChristian Graus17-Jul-02 23:25 
GeneralRe: Good, but... Pin
Joao Vaz18-Jul-02 0:47
Joao Vaz18-Jul-02 0:47 
This in teory will not compile ...
You must undef the min macro or put in the preprocessor configuration the definition NOMINMAX, this will disable the microsoft min/max macros ...

for instance if you used std::numeric_limits<int>::min() , this will trigger a ambiguous compilation error ...



Cheers,
Joao Vaz
The loved ones never really leave us , they are always alive on our hearts and minds.
GeneralRe: Good, but... Pin
Christian Graus18-Jul-02 12:21
protectorChristian Graus18-Jul-02 12:21 
GeneralRe: Good, but... Pin
Joao Vaz18-Jul-02 12:37
Joao Vaz18-Jul-02 12:37 
GeneralRe: Good, but... Pin
Christian Graus18-Jul-02 12:43
protectorChristian Graus18-Jul-02 12:43 
GeneralRe: Good, but... Pin
Joao Vaz19-Jul-02 1:18
Joao Vaz19-Jul-02 1:18 
GeneralRe: Good, but... Pin
Christian Graus19-Jul-02 3:28
protectorChristian Graus19-Jul-02 3:28 
GeneralRe: Good, but... Pin
Nish Nishant17-Jul-02 23:36
sitebuilderNish Nishant17-Jul-02 23:36 
GeneralRe: Good, but... Pin
Christian Graus18-Jul-02 12:14
protectorChristian Graus18-Jul-02 12:14 
GeneralRe: Good, but... Pin
Stefan Spenz18-Jul-02 0:02
Stefan Spenz18-Jul-02 0:02 
GeneralRe: Good, but... Pin
Joao Vaz18-Jul-02 0:52
Joao Vaz18-Jul-02 0:52 
GeneralRe: Good, but... Pin
Stefan Spenz18-Jul-02 1:04
Stefan Spenz18-Jul-02 1:04 
GeneralRe: Good, but... Has lots of typos Pin
Jon18-Jul-02 5:00
Jon18-Jul-02 5:00 
GeneralRe: Good, but... Pin
William E. Kempf18-Jul-02 10:55
William E. Kempf18-Jul-02 10:55 
GeneralRe: Good, but... Pin
Christian Graus18-Jul-02 12:20
protectorChristian Graus18-Jul-02 12:20 
GeneralRe: Good, but... Pin
Joao Vaz18-Jul-02 12:34
Joao Vaz18-Jul-02 12:34 
GeneralRe: Good, but... Pin
Ramon Casellas18-Jul-02 6:36
Ramon Casellas18-Jul-02 6:36 
GeneralRe: Good, but... Pin
Christian Graus18-Jul-02 12:42
protectorChristian Graus18-Jul-02 12:42 
GeneralRe: Good, but... Pin
Ramon Casellas18-Jul-02 6:42
Ramon Casellas18-Jul-02 6:42 

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.