Ad Code

Understanding Templates in C++: A Beginner's Guide

Templates in C++ 


C++ templates are a powerful feature that allows you to define generic classes and functions. This technique is called generic programming, and it allows you to write code that can work with a variety of data types.

Function templates are used to define a function that can take arguments of different data types. The syntax of a function template is similar to that of a regular function, but with a template declaration preceding it. The template declaration specifies a generic type parameter that will be replaced with a specific data type when the function is called.

Class templates are similar to function templates but are used to define generic classes. Like function templates, class templates also use a template declaration that specifies the generic type parameter. The class template can be used to create objects of different data types.

Templates in C++ can be very useful when you need to write code that can work with a variety of data types. They can save you a lot of time and effort by allowing you to write generic code that can be used with different data types. With templates, you can write code that is more flexible and reusable.

Program:-
 #include<iostream>
 using namespace std;
 template<class T>T add(T&a,T&b)
 {
 T result =a+b;
 return result;
 }
 int main()
 {
 int i=2,j=3;
 float m=2.2,n=1.2;
 cout<<"addition:"<<add(i,j);
 cout<<"addition:"<<add(m,n);
 return 0;
 }

Output:- 

addition: 5
addition: 3.4


Program:-
 #include<iostream>
 using namespace std;
 template<class T>
 class A
 {
  public:
       T num1=5;
       T num2=6;
        
  void add()
 {
 cout<<"addition"<<num1+num2;
 }
 };
 int main()
 {
    A<int>d;
     d.add();
     return 0;
 }


Output:-

Adddition: 11

Post a Comment

0 Comments

Ad Code