What are templates in C++?
Why Interviewers Ask This
This is a classic screening question for C++ roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
Templates enable generic programming — writing code that works with any type without repeating code. The compiler generates type-specific code at compile time (zero runtime overhead). Function templates: template<typename T> T maximum(T a, T b) { return (a > b) ? a : b; } // Usage: auto m1 = maximum(3, 7); // T = int auto m2 = maximum(3.14, 2.71); // T = double auto m3 = maximum(std::string("cat"), std::string("dog")); // T = string. Class templates: template<typename T> class Stack { std::vector<T> data; public: void push(T value) { data.push_back(value); } T pop() { T v = data.back(); data.pop_back(); return v; } bool empty() const { return data.empty(); } }; Stack<int> intStack; Stack<std::string> strStack;. Multiple type parameters: template<typename K, typename V> class Pair { public: K key; V value; };. Non-type template parameters: template<int N> class FixedArray { int data[N]; }; FixedArray<10> arr;. Template specialization: provide a specific implementation for a particular type: template<> void print<bool>(bool b) { std::cout << (b ? "true" : "false"); }. Variadic templates (C++11): template<typename... Args> void log(Args... args) { (std::cout << ... << args) << "\n"; } log(1, " + ", 2, " = ", 3);. Templates power the entire STL — containers and algorithms are all templates.
Pro Tip
This topic has C++-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.