The following is meant as a side-by-side comparison between Regular Functions and Function Templates:
Regular Function | Function Templates |
---|---|
#include <iostream> using namespace std; int maxi(int a, int b) { return a > b ? a : b ; } |
#include <iostream> using namespace std; template <class T> T maxi(T a, T b) { return a > b ? a : b ; } |
The following is meant as a side-by-side comparison between Ordinary Classes and Class Templates:
Ordinary Class | Class Template |
---|---|
#include <iostream> using namespace std; //1. creating a class class my_class { int i; public: my_class(int a); void show(); }; //2. defining member functions my_class::my_class(int a) { i=a; } void my_class::show() { cout << "i is: " << i << endl; } int main() { //3. creating specific instances my_class intobj(10); my_class intobj2(20); intobj.show(); intobj2.show(); return 0; } |
#include <iostream> using namespace std; //1. creating a class template template <class T> class my_class { T i; public: my_class( T a); void show(); }; //2. defining member function for class template template <class T> my_class<T>::my_class( T a) { i=a; } template <class T> void my_class<T>::show() { cout << "i is: " << i << endl; } int main() { //3. creating specific instances my_class<int> intobj(10); my_class<char> charobj('A'); intobj.show(); charobj.show(); return 0; } |
Notice that in the ordinary class, we can only create instances of integer objects. In the class template, we have created one instance of an integer object and one instance of a char object by specifying the type in angle brackets.