Templates in C++
In C++, templates are the foundation for generic programming. A template
is a blueprint or formula for creating a generic class or a function. For example, the standard library defines a single class template that defines what it means to be a vector. That template is used to generate any number of type-specific vector class, for example, vector<int> or vector<string>.
Function Template Example
Here is an example of a function template
that returns the sum of two values.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;
template <typename T>
inline T Sum (T const& a, T const& b) {
return a + b;
}
int main() {
int i = 39, j = 20;
cout << Sum(i, j) << endl;
double f1 = 13.5, f2 = 20.7;
cout << Sum(f1, f2) << endl;
string s1 = "Hello", s2 = "World";
cout << Sum(s1, s2) << endl;
}
The output of the above code is:
1
2
3
59
34.2
HelloWorld
Class Template Example
Here is an example of a class template
to define class Stack<> and implement generic method to push and pop the elements from the stack.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <vector>
using namespace std;
template <class T>
class Stack {
private:
vector<T> elems;
public:
void push(T const& );
void pop();
T top() const;
bool empty() const {
return elems.empty();
}
};
template <class T>
void Stack<T>::push (T const& elem) {
elems.push_back(elem);
}
template <class T>
void Stack<T>::pop () {
if (elems.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");
}
elems.pop_back();
}
template <class T>
T Stack<T>::top () const {
if (elems.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
return elems.back();
}
int main() {
try {
Stack<int> intStack;
Stack<string> stringStack;
intStack.push(7);
cout << intStack.top() << endl;
stringStack.push("hello");
cout << stringStack.top() << endl;
stringStack.pop();
stringStack.pop();
} catch (exception const& ex) {
cerr << "Exception: " << ex.what() << endl;
return -1;
}
}
The output of the above code is:
1
2
3
7
hello
Exception: Stack<>::pop(): empty stack