Created
March 2, 2021 06:10
-
-
Save vineethm1627/8d1467b2c4d5bb4b7e0661ca949a676f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/********************************************/ | |
/************* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Template specialization in classes: