C++ Function
Templates
Write one function that works with any data type: learn how the compiler generates type-safe code from a single blueprint.
The Repetition Problem
Imagine you need a function that returns the larger of two values. Without templates you would write separate overloads for every type:
int maxVal(int a, int b) { return (a > b) ? a : b; } double maxVal(double a, double b){ return (a > b) ? a : b; } char maxVal(char a, char b) { return (a > b) ? a : b; }
What Is a Function Template?
A function template is a blueprint that tells the compiler: "here is the logic; plug in whatever type is needed." The compiler then generates actual functions for each type used.
Key Vocabulary
T) that stands in for any type.int, double) substituted for T.T from the arguments you pass, without you specifying it.Template Syntax
template <typename T> T maxVal(T a, T b) { return (a > b) ? a : b; }
How Instantiation Works
typename vs class
| typename T | class T | |
|---|---|---|
| Meaning | T is any type | T is any type |
| Works with int, double, etc. | ✓ | ✓ |
| Works with class/struct | ✓ | ✓ |
| Convention | Modern preferred | Legacy, still common |
How to Write a Template
template<typename T> above the function.T in the return type and parameter list.T, or you specify it explicitly.T supports the operations used (e.g., operator>).Example 1: Generic Swap
template <typename T> void mySwap(T& a, T& b) { T temp = a; a = b; b = temp; } int main() { int x = 5, y = 10; mySwap(x, y); // T = int std::string s1 = "hello", s2 = "world"; mySwap(s1, s2); // T = std::string }
Example 2: Multiple Type Parameters
Templates can have more than one type parameter. Use distinct names like T and U:
template <typename T, typename U> void printPair(T first, U second) { std::cout << first << ", " << second << "\n"; } // Usage: printPair(42, "hello"); // T=int, U=const char* printPair(3.14, 100); // T=double, U=int
Example 3: Deduced Return Type
In C++14 and later you can let the compiler deduce the return type with auto:
template <typename T, typename U> auto add(T a, U b) { return a + b; } auto r1 = add(3, 4.5); // double (int + double) auto r2 = add(1, 2); // int (int + int)
Implicit vs Explicit Calls
template <typename T> T square(T x) { return x * x; } // Implicit deduction: square(5); // T = int square(2.5); // T = double // Explicit specification: square<double>(5); // T = double (5 promoted)
func<Type>(...). Needed when deduction would be wrong or ambiguous.When Deduction Fails
template <typename T> T maxVal(T a, T b) { return (a > b) ? a : b; } maxVal(3, 4.5); // ERROR: T=int or T=double?
Both arguments must yield the same T. The compiler sees int and double and cannot pick one.
maxVal<double>(3, 4.5);maxVal(static_cast<double>(3), 4.5);template<typename T, typename U> instead.Templates vs Overloading
| Function Template | Overloading | |
|---|---|---|
| Code written | Once | Once per type |
| Type safety | Compile-time | Compile-time |
| Logic varies per type? | No: same logic | Yes: each can differ |
| Performance | Same as hand-written | Same as hand-written |
| Error messages | Can be verbose | Clear and direct |
Common Mistakes
.cpp file causes linker errors. Keep templates in header files.maxVal(3, 4.5) when both params are T fails deduction. Cast or add a second parameter.operator>, the template won't compile for that type.Quick Reference Summary
| Concept | Syntax / Detail |
|---|---|
| Declare template | template<typename T> |
| Multiple params | template<typename T, typename U> |
| Implicit call | maxVal(3, 7) |
| Explicit call | maxVal<double>(3, 7) |
| Where to define | In header files (.h / .hpp) |
| Constraint check | Ensure T supports all used operators |
Question 1 of 5
What is the primary purpose of a function template in C++?
Question 2 of 5
Given the template below, what is the output?
template <typename T> T triple(T x) { return x * 3; } std::cout << triple(4);
Question 3 of 5
Why does maxVal(3, 4.5) fail to compile when maxVal uses a single template<typename T>?
Question 4 of 5
Where should a function template's definition be placed?
Question 5 of 5
What does the following code print?
template <typename T, typename U> auto add(T a, U b) { return a + b; } std::cout << add(2, 3.5);