Skip to content

Instantly share code, notes, and snippets.

@vineethm1627
Created March 2, 2021 06:10
Show Gist options
  • Save vineethm1627/8d1467b2c4d5bb4b7e0661ca949a676f to your computer and use it in GitHub Desktop.
Save vineethm1627/8d1467b2c4d5bb4b7e0661ca949a676f to your computer and use it in GitHub Desktop.
/********************************************/
/************* HOW TO USE TYPES *************/
/********************************************/
#include <iostream>
using namespace std;
/* This can be used indifferently for any type */
template<typename T>
void print_data(T output){
cout << output << endl;
}
/* TEMPLATE SPECIALIZATION: it behaves differently for int type */
template<>
void print_data(int output){
cout << output << ".000" << endl;
}
/* Should you use two types, you need this */
template<typename U, typename S>
void print_double_data(U first, S second){
cout << first << " " << second << endl;
}
int main() {
double d = 5.5;
string s("Hello World");
int i = 10;
print_data(d); // it functions with a double...
print_data(s); // ...and it functions with a string, also
print_data<int>(i); // let's invoke template specialization!
print_double_data(d,s); // you need two different types U and S: using a single typename would result in an error
print_double_data(s,s); // of course, it functions even if U and S are same type
return 0;
}
@vineethm1627
Copy link
Author

In case of regular class templates, the way the class handles different data types is the same; the same code runs for all data types.
Template specialization allows for the definition of a different implementation of a template when a specific type is passed as a template argument.

@vineethm1627
Copy link
Author

vineethm1627 commented Mar 2, 2021

Template specialization in classes:

template <class T>
class MyClass {
 public:
  MyClass (T x) {
   cout <<x<<" -  not a char"<<endl;
  }
};

template < >
class MyClass<char> {
 public:
  MyClass (char x) {
   cout <<x<<" is a char!"<<endl;
  }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment