Template in C++ | Code2night.com
Code2night
  • Home
  • Blogs
  • Guest Posts
  • Tutorial
  • Post Blog
  • Register
  • Login
  1. Home
  2. Blogpost

Template in C++

Date- Dec 09,2023

1573

Templates in C++ allow you to construct generic code that can deal with multiple data types without having to replicate the code for each one. In C++, templates are fundamental for constructing flexible and reusable classes and functions. In C++, there are two types of templates: function templates and class templates.

1. Function Templates:

Function templates allow you to create generic functions that can operate on different data types. You define a function template by specifying a placeholder for the data type. Here's a basic example of a function template that swaps two values of any data type:



#include<iostream.h>

#include<conio.h>

template<class T>

void display(T x,T y)

{

T result;

result=x+y;

cout<<"Addition is\n"<<result<<endl;

}

void main()

{

clrscr();

display(4,5);

display(5.7,6.7);

getch();

}




2. Class Templates:

Class templates allow you to define generic classes. You can create a class template with one or more template parameters. Here's a simple example of a class template for a stack data structure:

#include<iostream.h>

#include<conio.h>

template<class T>

class A

{

T a;T b;

public:

void display();

void print();

};

template<class T>

void A<T>::display()

{

cout<<"enter the value of a\n";

cin>>a;

cout<<"Enter the value of b\n";

cin>>b;

}

template<class T>

void A<T>::print()

{

cout<<a<<endl<<b;

}

void main()

{

clrscr();

A<int> a1;

a1.display();

a1.print();

getch();

}








Comments

Tags

LinkedinLogin
LinkedinProfile
GetLinkedinProfile
C#
Aspnet
MVC
Linkedin
ITextSharp
Export to Pdf
AspNet Core
AspNet
View to Pdf in Aspnet
Model Validation In ASPNET Core MVC 60
Model Validation
Model Validation In ASPNET Core MVC
Model Validation In ASPNET
Image Compression in AspNet
Compress Image in c#
AspNet MVC
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1210
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp Join Us On Facebook

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Panipat
  • info@Code2night.com

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2025 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Terms & Conditions
  • Refund Policy
  • About Us
  • Privacy Policy
  • Json Beautifier
  • Guest Posts