What is template in CPP
Ans:- A C++ template is an advanced feature of C++ that allows us to define the Generic class and Generic function. So if you provide the Generic Programming. Generic Programming is a technique where Generic type uses a Parameter (), an Algorithm. So we can work for a variety of Datatype. What is template in CPP
Learn Others from 1st-year click
A templates can be present into two way:-
1. Function Templates
2. Class Templates
1. The function of Templates.
:-We can define a template of the function. for ex:- If you will have a function that you can create different datatypes as an argument in a function. So by using function templates, we can refresh the Function Overloading.
Advantages of Function Templates.
- The generic function we the concept of function Templates.
- The generic function defined a set of Operators that can be applied to the various datatype.
- The type of data that a function will operate on remains on the type of data pass as a Parameter.
- generic Function can be created by Templates Keyword. Templates what function will do.
Syntax:-
template<class T>return type frame(parameter)
{
//body of the function
}
What is template in C++
Example through Function Templates:-
#include<iostream.h>
#include<conio.h>
void sum (T a. T b)
{
cout <<“sum=”<<( a+b )<< endl;
}
void main()
{
float n1=200.10, n2=300.20;
long k1=500, k2=600;
int a=10,b=20;
cout<<“sum=”<<sum(a,b)<<endl;
cout<<“sum=”<<sum(n1,n2)<<endl;
cout<<“sum=”<<sum(k1,k2)<<endl;
getch();
}
Output:- sum=500.30
sum=1100
sum=30
(In Float, Long and Integer)
CPP template
2. Class Templates:-
The class template also is defined similarly to the function template when the class templates concept function.
templates are known as the generic class.
Syntax:- template<classT> class < Cname> { private: T var1; T var2; public: Cname (T X) { }; void main() { Cname<int> obj(100); Cname<char>obj('a');
Template in CPP
Example of Class Template in C++ :-
#include<iostream.h> #include<conio.h> template<class T> class test { private: T a; public: test (T X) { a=X; } void show() { cout<<"a="<<a<<endl; } }; void main() { test <int>t1(100); test <char>t2('a'); test <float>t3(600.20); t1.show(); t2.show(); t3.show(); getch(); }
Output:- 100
a
600,20
C++ template function
Hello, Student, I hope you will learn about C Template. If you have any queries about this article please don’t be hesitate to tell us. Read More…