Revision on C++

Posted on Updated on

Just revising on C++ for a bit. Todays topic, Templates.

What is a template?

A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.

There is a single definition of each container, such as vector, but we can define many different kinds of vectors for example, vector or vector .

Ok cool, lets try with the code below:

#include <iostream>
#include <string>

using namespace std;

template<typename T>
inline T const& Max(T const& a, T const&b) {
	return a < b ? b:a;

int main() {
	int i = 39;
	int j = 20;

	cout << "Max(i, j): " << Max(i, j) << endl;

	double f1 = 00000.2;
	double f2 = 00.0002;

	cout << "Max(f1, f2): " << Max(f1, f2) << endl;	

	string s1 = "you dont need me man i ";
	string s2 = "dont need you";

	cout << "Max(s1, s2): " << Max(s1, s2) << endl;

Above code gives us the max value of i, j, f1, f2, s1 and s2 which is shown below when executed:

benjamin.lo% c++ TemplateTest.cpp
benjamin.lo% ./a.out
Max(i, j): 39
Max(f1, f2): 0.2
Max(s1, s2): you dont need me man i


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s