C++ Templates: Generic Classes, Functions, and Type-Safe Reuse
What is C++ Templates: Generic Classes, Functions, and Type-Safe Reuse? Templates are compile-time blueprints that allow functions and classes to operate with generic types without sacrificing type safety or runtime performance. Dur...
How do function templates and class templates work in C++, and how does template instantiation generate type-safe code at compile time?
Explanation & In-Depth Details
```text
Template Blueprint: template <typename T> T findMax(T a, T b)
│
├───► Called with findMax(10, 20) ──► Compiler generates: int findMax(int, int)
└───► Called with findMax(3.14, 2.71) ──► Compiler generates: double findMax(double, double)
```
2. Zero Runtime Overhead:
Templates avoid type-erasure and boxing overhead, enabling the compiler to inline code and perform deep optimizations.
Code Example
#include <iostream>
#include <string>
// 1. Generic Function Template
template <typename T>
T findMax(T a, T b) {
return (a > b) ? a : b;
}
// 2. Generic Class Template
template <typename T, int Capacity = 10>
class FixedBuffer {
private:
T data[Capacity];
int count = 0;
public:
void push(T val) {
if (count < Capacity) data[count++] = val;
}
void print() const {
for (int i = 0; i < count; ++i) std::cout << data[i] << " ";
std::cout << "\n";
}
};
int main() {
// Function Template deduction
std::cout << "Max int: " << findMax(10, 25) << "\n";
std::cout << "Max double: " << findMax(4.55, 2.11) << "\n";
// Class Template instantiation
FixedBuffer<std::string, 3> strBuf;
strBuf.push("C++");
strBuf.push("Templates");
strBuf.push("Rocks");
std::cout << "Buffer contents: ";
strBuf.print();
return 0;
}Interview Question & Tips
A: The compiler must see the full template implementation at the point of instantiation to generate the specialized machine code for the target type during translation unit compilation.
Q: What is template specialization?
A: Template specialization allows developers to define custom, optimized implementations of a generic template for a specific type (e.g. `std::vector<bool>`).
Best Practices
• Use `typename` or `class` interchangeably in template parameter lists.
• Constrain template types with C++20 Concepts (`template<std::integral T>`) for clearer compiler diagnostics.
This study reference for C++ Templates: Generic Classes, Functions, and Type-Safe Reuse is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: