Advanced C++: Template, Function Template, and Class Template

Home / Advanced C++: Template, Function Template, and Class Template

Maybe, template is one of C++ key feature that is rarely owned by other programming language. This feature is already supported by all modern / standard C++ compilers. Using template, we can create a single generic function or generic class. Simply we can create one general function or general class and whenever a similiar function or class is met, we can instance it with those problems.

Template is defined using C++ keyword, template.

Template is also the fundamental / the basis for creation of Standard Template Library (STL). STL is a collection of function or data structure that can be used for any data type. Yes, you can create a list of integer, a queue of float, a stack of string, etc with single class.

Function Template

Function template is a generic function. You create a function that does the job and every data can be passed to it, without recode the function.

Function Template with Generic Type

To create a function template, we did the same thing as creating a simple function. The difference lies on parameter type.

Here is the generic function template declaration.

template <class T>
return_type function_name( parameter1, parameter2, ...) {
	statements;
}

The template keyword describe that this function is generic function. While T on <class T> is called as generic type. It is a placeholder. This type then will be used as parameter declaration of that function. Let’s see a simple example:

#include <iostream>
using namespace std;

template
void SwapVariable(T& x, T& y) {
	T z;

	z = x;
	x = y;
	y = z;
}

int main() {
	int a = 10, b = 15;
	float c = 3.14, d = 1.15;

	SwapVariable(a,b);
	SwapVariable(c,d);

	cout<<a<<' '<<b<<endl;
	cout<<c<<' '<<d<<endl;
	return 0;
}

Write, compile, and run the above code. What are the output?

If you observe carefully, you can see that we only define one function SwapVariable but we use if for 2 different data type: int and float. This is the power of generic function.

Function Template with Two or More Generic type

When you see the declaration, the data type used for the argument are T. This indicated that both argument HAVE the same data type, regardless what type. How can we specify two or more different data type?

template <class T, class U>
void Writeln(T x, U y) {
	cout<<x<<' '<<y<<endl;
}

The above code is a generic function with two different generic type, T and U respectively. Those T and U can be replaced with any other type, such as: int, float, char, etc. Interesting, huh? ๐Ÿ˜€

In general, the generic types are declared inside template< >. If you want three you should declare three inside them. How about four?

template<class TYPE1, class TYPE2, class TYPE3, class TYPE4>
void aFunction(TYPE1 w, TYPE2 x, TYPE3 y, TYPE4 z) {
	// do somethings
}

Function Template Overload

Just like ordinary function, function template can be overloaded. This code will give you a hint to do so:

#include
using namespace std;

template<class TYPE1>
void writeIt(TYPE1 x) {
	cout<<x<<endl;
}

template<class TYPE1, class TYPE2>
void writeIt(TYPE1 x, TYPE2 y) {
	cout<<x<<endl;
	cout<<y<<endl;
}

int main() {
	writeIt(3);
	writeIt(1, 2.5);

	return 0;
}

See? We have overloaded writeIt function for our need.

Generally speaking, function template is used if we have generic algorithm and can be used to similiar data type. Later, the compiler will create a specific instance of function for given data type. It is done in compiler level, you just need to write once.

Class Template

Besides function template, C++ also provide Class Template. Similiar to function template. class template can be used to create generic class for any similiar functional of different type of class.

Class Template with One Generic Type

In principle, defining class template is similiar to defining ordinary class. Here is a generic class template declaration:

template <class T>
class class_name {
access specifier:
	data
	methods
};

To instantiate a class template, we have general statement like this:

class_name < data_type > instance_name;

Now let see the simple example:

#include <iostream>
using namespace std;

template<class T>
class EXAMPLE {
public:
	EXAMPLE(T xx) { x = xx; }
	void showOff() { cout<<x<
private:
	T x;
};

int main() {
	EXAMPLE<int>  A(10);
	EXAMPLE<string>  B("Xathrya Sabertooth");
	EXAMPLE<float>  C(3.14);
	EXAMPLE<char>  D('A');

	A.showOff();
	B.showOff();
	C.showOff();
	D.showOff();

	return 0;
}

compile and see the result.

Here in our example, we have EXAMPLE class with one generic type. The EXAMPLE class then can be instantiate to different object with different characteristic, A with int, B with string, C with float, D with character. Everything from a same class.

Class Template with Two or More Generic Type

Similiar to generic function declaration, a class template definition can be composed of two or more generic type. Here is a sample code of it:

#include <iostream>
using namespace std;

template<class TYPE1, class TYPE2>
class EXAMPLE {
	TYPE1 x;
	TYPE2 y;

public:
	EXAMPLE(TYPE1 xx, TYPE2 yy) {
		x = xx;
		y = yy;
	}
	void showOff() {
		cout<<x<<' '<<y<<endl;
	}
};

int main() {
	EXAMPLE<int, float>  A(15, 4.67);
	EXAMPLE<string, int>  B("Xathrya",30);

	A.showOff();
	B.showOff();
}

Write, compile, and run the code. What is the result? ๐Ÿ˜€

Template with typename keyword

In previous example we always use keyword class to define a generic type. There is another way to define a generic type, using typename class. Essentially, the declaration by class and declaration by typename is interchangable. So these declaration for function template is equivalence:

template<class T>
void function1(T t);

template<typename T>
void function2(T t);

So let’s summarize this article. What is the benefit using template?

  • Save up time: why would you write “same” code everytime? Write once for similiar condition. Besides, you can read and write fewer code ๐Ÿ˜€
  • Can be used for another situation: function and class template can be used for any data type.
  • Improving program flexibility

,

About Author

about author

xathrya

A man who is obsessed to low level technology.

2 Comments
  1. Beginning C++: Primitive Types and Identifiers - Xathrya.ID

    […] knows object through identifier. Identifier can be a variable name, constants, functions, classes, template, even […]

  2. Separating CPP Template Declaration and Implementation - Xathrya.ID

    […] Templates are a feature of the C++ programming language that allow function and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one. The C++ Standard Library specify a special section for heavy use of template, called Standard Template Library. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Social media & sharing icons powered by UltimatelySocial