🧩 C++ programming tutorial for beginners · Class 11 · Lesson 9 of 18 · Free
Templates in C++ – Write Code Once for Any Type
⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in
In this lesson you will
- Write a function template and let the compiler work out the type
- Build a class template such as Stack<T> and use it with different types
- Use templates with your own classes and fix common template errors
You wrote a function to find the bigger of two marks. Now you need the same for prices (double) and for names (string). Copying it three times means three places to fix every bug. A template lets you write it once and C++ makes each version for you.
What is a function template in C++?
A template is a recipe for a function or class, with a placeholder for the type. template <typename T> says "T stands for some type, to be filled in later".
When you call biggest(45, 78), the compiler sees two ints and writes an int version. Calling it with doubles or strings makes those versions too. This happens at compile time.
In Lesson 5 you already used templates: vector<int> and map<string, int> are class templates from the STL.
Try it: call biggest with two chars, like 'A' and 'C'.
Higher marks: 78 Costlier item: Rs 120.25 Later in the roll list: Meena
💡 Strings compare in dictionary order, so "Meena" > "Kiran" because M comes after K.
How does C++ decide the template type T?
The compiler works out T from the arguments. This is called template argument deduction. biggest(3, 9) gives T = int.
If the two arguments have different types, like 3 and 4.5, deduction fails: T cannot be int and double at once. Write the type yourself: biggest<double>(3, 4.5). Then 3 is turned into 3.0.
A template can loop over any container too. Here total works for a vector of ints and a vector of doubles. T() gives a zero of that type.
Try it: call total on a vector<string> of {"Ra", "ma", "n"}. Adding strings joins them!
4.5 Runs: 59 Fees: Rs 349.75
What is a class template in C++?
A class can be a template too. Stack<T> below is a stack: the last thing you push is the first you pop, like plates in the canteen.
You write the type when you create an object: Stack<int> or Stack<string>. Each is a separate class made from the same recipe.
Inside, the stack keeps a vector<T>, so it can hold as many items as needed.
Try it: make a Stack<double> of bills and pop the last one.
Top plate: 2, plates: 2 Undo: made it bold
💡 top() on an empty stack would read past the end. Check empty() first, as a real program must.
Can a C++ template have more than one parameter?
Yes. template <typename K, typename V> has two type parameters, like map<K, V> in the STL.
A template parameter can also be a number fixed at compile time, like int N. Then each FixedList<T, N> has room for exactly N items, decided when you compile.
Here Entry<K, V> pairs a key with a value, and FixedList<T, 7> holds one week of attendance.
Try it: change 7 to 5 for a school week and remove two days from the list.
Coach S3 -> 42 17 -> 88.5 PPAPPPP
How do C++ templates work with my own classes?
A template uses whatever operations its code needs. biggest uses >, so any type with a > works, including your own class if you overload > (Lesson 8).
If your class has no >, the code does not compile, and the error points into the template. Read such errors from the line that mentions YOUR call.
This is the big idea of the STL: sort, max and set work with your classes as long as you give them the operators they need.
Try it: delete operator> from Player and run. Then read the error.
Top scorer: Anjali (64)
💡 Templates are made at compile time, so they cost no extra time when the program runs.
🤔 Predict the output
Think like C++: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T twice(T x) {
return x + x;
}
int main() {
cout << twice(5) << " " << twice(string("ab")) << "\n";
return 0;
}
Question 2. What does this print?
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
T sumAll(const vector<T>& v) {
T s = T();
for (const T& x : v) s += x;
return s;
}
int main() {
vector<double> v = {1.5, 2.5};
cout << sumAll(v) << "\n";
return 0;
}
Question 3. On this compiler (char 1, int 4, double 8 bytes), what does this print?
#include <iostream>
using namespace std;
template <typename T>
void bytes(T x) {
cout << sizeof(x);
}
int main() {
bytes('a');
bytes(10);
bytes(2.5);
cout << "\n";
return 0;
}
🧩 Your challenge
Write a class template Queue<T> for a ticket counter: the first to join is the first served. It needs join(x), serve() that returns and removes the front item, size() and empty(). Use it twice: Queue<string> for people and Queue<int> for token numbers. Expected output: Serving Ravi Serving Sana Still waiting: 1 Token 501 Token 502
Serving Ravi Serving Sana Still waiting: 1 Token 501 Token 502
⚠️ Common mistakes (and how to fix them)
❌ Wrong
#include <iostream>
using namespace std;
template <typename T>
T biggest(T a, T b) { return a > b ? a : b; }
int main() {
cout << biggest(3, 4.5) << "\n";
return 0;
}
Line 8: error: no matching function for call to 'biggest'
✅ Right
#include <iostream>
using namespace std;
template <typename T>
T biggest(T a, T b) { return a > b ? a : b; }
int main() {
cout << biggest<double>(3, 4.5) << "\n";
return 0;
}
3 is int and 4.5 is double, so the compiler cannot pick one T. Say the type yourself with biggest<double>, or pass 3.0.
❌ Wrong
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T biggest(T a, T b) { return a > b ? a : b; }
struct Book {
string title;
int pages;
};
int main() {
Book a{"Gitanjali", 104}, b{"Godan", 312};
cout << biggest(a, b).title << "\n";
return 0;
}
Line 6: error: invalid operands to binary expression ('Book' and 'Book')
✅ Right
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T biggest(T a, T b) { return a > b ? a : b; }
struct Book {
string title;
int pages;
bool operator>(const Book& o) const { return pages > o.pages; }
};
int main() {
Book a{"Gitanjali", 104}, b{"Godan", 312};
cout << biggest(a, b).title << "\n";
return 0;
}
The template uses >, but Book does not have one. Overload operator> (Lesson 8) so the template knows how to compare books.
❌ Wrong
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
T average(const vector<T>& v) {
T sum = T();
for (const T& x : v) sum += x;
return sum / v.size();
}
int main() {
vector<int> marks = {7, 8};
cout << average(marks) << "\n";
return 0;
}
Compiles and runs, but prints: 7 ⏎
✅ Right
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
double average(const vector<T>& v) {
T sum = T();
for (const T& x : v) sum += x;
return (double)sum / v.size();
}
int main() {
vector<int> marks = {7, 8};
cout << average(marks) << "\n";
return 0;
}
With T = int the template does int division and returns an int, so 7.5 becomes 7. Return double and divide as double.
📌 Remember
- template <typename T> writes one recipe that works for many types.
- The compiler deduces T from the arguments; write biggest<double>(...) when types differ.
- Class templates like Stack<T> or vector<T> take the type in angle brackets.
- Templates can have several type parameters and number parameters like int N.
- A template works with your class only if the class has the operators it uses.
Finished the quiz and the challenge?
Questions students ask
What is the difference between typename and class in a template?
In template <typename T> and template <class T> the two words mean exactly the same. typename is clearer because T can be any type, not only a class.
Why must templates be written in header files?
The compiler needs the full template code at the place where you use it, to make the version for your type. So templates usually live completely in .h files, not split into .h and .cpp like normal classes (Lesson 6).
Do templates make programs slower?
No. The versions are made at compile time, so a template call runs as fast as a normal function. They can make compiling a bit slower and the program file a bit bigger.
Are C++ templates the same as generics in Java?
They look alike, but C++ templates make a real separate version for each type at compile time. Java generics keep one version and check types only while compiling. C++ templates can also take numbers, like int N.