Introduction
C++, or "C with Classes," is a high-level, general-purpose programming language. Danish computer scientist Bjarne Stroustrup developed it to expand the C programming language. It is nearly always written as compiled code. In this blog, we will learn about class template specialization in C++ with the help of examples.
What is a Template in C++?
Templates are strong C++ capabilities that allow us to create generic programs. Templates determine the behavior of class and function families. It is frequently necessary to treat unusual types or non-types differently. As a result, you may fully customize templates while using template specialization in C++.
There are two ways we can implement template specialization in C++:
- Function Templates
- Class Templates
Class Template
- Class templates may be used to construct a single class that works with several data types.
- Class templates are helpful since they make our code shorter and easier to manage.
- A class template begins with the keyword "template," then template parameter(s) inside <>, then the class declaration.
- T is a placeholder for the data type used in the template parameter, and class is a keyword.
- Class templates are partially specialized.
Syntax:
template <class T>
class className {
private:
T var;
... .. ...
public:
T functionName(T arg);
... .. ...
};
Example:
#include <iostream>
using namespace std;
template<class t1>
class numbers
{
t1 x;
public:
void getdata()
{
cin>>x;
}
void display()
{
cout<<"Your entered value is:"<<endl;
cout<<"x="<<x<<endl;
}
};
int main()
{
numbers<int> s1;
numbers<float> s2;
cout <<"Enter an Integer value:"<<endl;
s1.getdata();
s1.display();
cout <<"Enter Float value"<<endl;
s2.getdata();
s2.display();
return 0;
}
Output:
Dry run:
Function Template
A function template begins with the keyword template, then template parameter(s) inside <>, and the function declaration.
Syntax:
template <class T>
T Name(T p1, T p2, ...) {
}
Here p is the parameter.
Example:
#include <iostream>
using namespace std;
template<class t1,class t2>
void product(t1 x,t2 y) // defining template function
{
cout<<"Product="<<x*y<<endl;
}
int main()
{
int p,q;
float s,r;
cout<<"Enter two integer data: ";
cin>>p>>q;
product(p,q);
cout<<"Enter two float data: ";
cin>>s>>r;
product(s,r);
return 0;
}
Output:
Dry run:
Step 1:
Step 2:
Try and compile with online c++ compiler.