C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Code Snippets » C/C++ Code Snippets

C++ program to demonstrate example of Templates.

By: IncludeHelp, On 25 OCT 2016






Here we will learn about C++ Templates, what are the templates, how they work and how to declare, define and use?

C++ Templates

C++ introduced concept of templates, by using C++ templates we can work with generic types. Usually we are able to work with predefine data type like int, char, float etc.
Reference: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-096-introduction-to-c-january-iap-2011/lecture-notes/MIT6_096IAP11_lec09.pdf

For example - if there is no template then we will have to repeat the same code for different kind of data types, using generic types through template - we can able to use any kind of data type without repeating the code for different kind of data types.

Suppose you are writing code to add two numbers you will have to write different functions for integer data addition, float data addition and so on. But if we will use template one function with template (generic type data type) can be used for all kind of addition.

In this example, we are creating a class Numbers which has two generic type variable x and y; we will create two objects NUM1 and NUM2 which will accept integer and float type data types.

C++ program - Demonstration of Template in C++ programming language

Let’s consider the example

#include <iostream>
using namespace std;

template <typename TYPE>

class Numbers
{
	private:
	TYPE x, y;
	public:
	//constructor
	Numbers(const TYPE a, const TYPE b) : x(a), y(b) {}
	TYPE getX() { return x; }
	TYPE getY() { return y; }
};

int main() 
{
	Numbers<float> NUM1(100, 200);
	cout<<"Values with integer numbers: ";
	cout << NUM1.getX() << ", " << NUM1.getY() << endl;
	
	Numbers<float> NUM2(100.20, 150.69);
	cout<<"Values with float numbers: ";
	cout << NUM2.getX() << ", " << NUM2.getY() << endl;
	return 0;
}
    Values with integer numbers: 100, 200 
    Values with float numbers: 100.2, 150.69