Template Specialization in C++

C++Server Side ProgrammingProgramming

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<iostream>
using namespace std;
template<typename T>
void my_function(T x) {
   cout << "This is generalized template: The given value is: " << x << endl;
}
template<>
void my_function(char x) {
   cout << "This is specialized template (Only for characters): The given value is: " << x << endl;
}
main() {
   my_function(10);
   my_function(25.36);
   my_function('F');
   my_function("Hello");
}

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<iostream>
using namespace std;
template<typename T>
class MyClass {
   public:
      MyClass() {
         cout << "This is constructor of generalized class " << endl;
      }
};
template<>
class MyClass <char>{
   public:
      MyClass() {
         cout << "This is constructor of specialized class (Only for characters)" << endl;
      }
};
main() {
   MyClass<int> ob_int;
   MyClass<float> ob_float;
   MyClass<char> ob_char;
   MyClass<string> 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
raja
Published on 28-May-2019 11:59:41
Advertisements