C++ Function Templates
In this page:
Defining Function Templates
A function template defines a generic function blueprint: you write the template keyword followed by a list of type parameters in angle brackets, then a normal-looking function signature that uses those parameter names in place of concrete types.
Example: Defining Function Templates
#include <iostream>
template <typename T>
T square(T x) {
return x * x;
}
int main() {
std::cout << square(5) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Calling Function Templates
You can call a function template explicitly by specifying the type inside angle brackets yourself, or simply call it like a normal function and let the compiler deduce the type automatically from the arguments you pass — the latter is far more common in practice.
Example: Calling Function Templates
#include <iostream>
template <typename T>
T square(T x) {
return x * x;
}
int main() {
std::cout << square<double>(2.5) << std::endl;
std::cout << square(4) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Multiple Template Parameters
A single function template can declare multiple type parameters, letting one generic function handle several arguments of genuinely different, unrelated types in the same call rather than requiring them all to match.
Example: Multiple Template Parameters
#include <iostream>
template <typename T1, typename T2>
void showPair(T1 a, T2 b) {
std::cout << a << " " << b << std::endl;
}
int main() {
showPair(5, "hello");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Overloading Function Templates
You can overload a function template just like an ordinary function, either by providing a specific non-template overload for a particular type or by defining another template with a different number of parameters, and the compiler picks the best match.
Example: Overloading Function Templates
#include <iostream>
template <typename T>
T maxValue(T a, T b) {
return (a > b) ? a : b;
}
int maxValue(int a, int b, int c) {
return maxValue(maxValue(a, b), c);
}
int main() {
std::cout << maxValue(3, 7) << std::endl;
std::cout << maxValue(3, 7, 5) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Non-Type Template Parameters
Templates also accept non-type parameters — constant values like integers rather than types — which the compiler treats as compile-time constants inside the function body, useful for things like fixed buffer sizes baked in at instantiation.
Example: Non-Type Template Parameters
#include <iostream>
template <int N>
int multiplyByN(int x) {
return x * N;
}
int main() {
std::cout << multiplyByN<3>(5) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: