Function Templates, Class Templates & Custom Namespaces
Idea in plain words
Templates enable Generic Programming: Writing algorithms and data structures independent of specific data types.
Exam tip
High-yield exam topic (High).
Explanation
Templates are executed at compile-time via template instantiation. The compiler generates specialized machine code for each unique type parameter combination, avoiding runtime boxing/unboxing overhead while preserving compile-time type safety.
Key points
- Function Templates: template T findMax(T a, T b) generates concrete functions on-demand.
- Class Templates: template class Stack creates type-safe collections for int, float, or custom objects.
- Namespaces: Prevent global identifier naming collisions in large projects (namespace MyProject { int value; }).
- Using Directives: using namespace std brings entire namespace into scope; using std::cout brings specific symbols.
Example
Example
Namespace isolation: namespace Engineering { int calculate(); } namespace Business { int calculate(); }. No name collisions!
Code examples
// Generic Stack Implementation Using C++ Class Template
#include <iostream>
using namespace std;
template <typename T, int MAX_SIZE = 100>
class GenericStack {
private:
T elements[MAX_SIZE];
int topIndex;
public:
GenericStack() : topIndex(-1) {}
bool push(T val) {
if (topIndex >= MAX_SIZE - 1) return false;
elements[++topIndex] = val;
return true;
}
T pop() {
if (topIndex < 0) throw runtime_error("Stack Underflow");
return elements[topIndex--];
}
};
int main() {
GenericStack<int> intStack;
intStack.push(10); intStack.push(20);
cout << intStack.pop() << endl;
GenericStack<string> strStack;
strStack.push("Purbanchal"); strStack.push("University");
cout << strStack.pop() << endl;
return 0;
}
Exam questions
- [8 Marks] Design a generic Stack class using C++ class templates with push, pop, and isEmpty operations.
- [7 Marks] What are namespaces in C++? How do they prevent identifier collisions? Explain with code snippets.