Template Specialization in C++

In C++, the templates are used to create generalized functions and classes. So we can use any type of data like int, char, float, or some user defined data also using templates.

In this section, we will see how to use the template specialization. So now we can define some generalized template for different types of data. And some special template function for special type of data. Let us see some example to get better idea.

Example Code

#include
using namespace std;
template
void my_function(T x) {
   cout 
void my_function(char x) {
   cout 

Output

This is generalized template: The given value is: 10
This is generalized template: The given value is: 25.36
This is specialized template (Only for characters): The given value is: F
This is generalized template: The given value is: Hello

The template specialization can also be created for classes. Let us see one example by creating generalized class, and specialized class.

Example Code

#include
using namespace std;
template
class MyClass {
   public:
      MyClass() {
         cout 
class MyClass {
   public:
      MyClass() {
         cout  ob_int;
   MyClass ob_float;
   MyClass ob_char;
   MyClass ob_string;
}

Output

This is constructor of generalized class
This is constructor of generalized class
This is constructor of specialized class (Only for characters)
This is constructor of generalized class
Updated on: 2019-07-30T22:30:26+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements