Templates in C++

Article by: Manish Methani

Last Updated: October 15, 2021 at 2:04pm IST
4 min 19 sec read

What is Template ?

Suppose you written a program which sorts an list of integer datatypes. So you had written a function which sorts integer values. Then suddenly in future you got a requirement of sorting a list of double datatypes. Then you have to write another function which handles double values. Then you got a requirement of writing a character values. So yu have to write one more function.

So here comes Template into existence. Template accepts generic types . Any type you pass Template will handle it. You have to write a single function.

Syntax :-

#include 
using namespace std;
 
// One function works for all data types. 
template 
T myMax(T x, T y)
{
   return (x > y)? x: y;
}
int main()
{
  cout << myMax('a', 'z') << endl;   // call myMax for char
  cout << myMax(2, 4) << endl;  // Call myMax for int
  cout << myMax(3.0, 7.0) << endl; // call myMax for double
 
  return 0;
}

Output :-

z
4
7

Templates are expanded at compile time. First we call myMax function with char type. Then myMax function accepts parameter of char type. Second time we call myMax function with int type. Then myMax function accepts parameter of int type. Third time we call myMax function with double type. Then myMax function accepts parameter of double type.

Simplified Coding for Beginners.








Download the Codzify
Mobile App


Mobile App Development, Web App Development, Programming Languages, Latest Tech News & lot more.

Codzify Mobile App

A self-paced learning Courses Created by an Engineer
For Engineers.

Premium

The Complete Angular Course

Instructor: Manish Methani

Explore Curriculum
Free

C Programming for Absolute Beginners

Instructor: Manish Methani

Start Watching
Premium

Flutter Mobile App Development Course

Instructor: Manish Methani

Explore Curriculum
Free

Learn HTML, CSS & Bootstrap

Instructor: Manish Methani

Start Watching

Test your skills with these expert-led curated
Mock Tests.

C Programming Test

Test your C Programming skills with this comprehensive mock test on C Programming.

Take Test

Flutter Test

Solve most asked Interview Questions on Flutter and Test your foundational skills in flutter.

Take Test

GATE(CSE) Operating Systems

Solve most asked GATE Questions in Operating Systems and test your Gate Score.

Take Test

HTML,CSS Test

This is a mock test designed to help you assess your knowledge and skills in HTML and CSS.

Take Test

(GATE CSE) Data Structures & Algorithms Test

Solve most asked GATE Questions in Data Structures and Algorithms and test your Gate Score.

Take Test
include_once 'codzify-footer.php'; ?>