← Back to C++ Course | Chapter 11: Templates | Lesson 2 of 5

C++ Function Templates

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

cpp
#include <iostream>

template <typename T>
T square(T x) {
	return x * x;
}

int main() {
	std::cout << square(5) << std::endl;
	return 0;
}

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#include <iostream>

template <int N>
int multiplyByN(int x) {
	return x * N;
}

int main() {
	std::cout << multiplyByN<3>(5) << std::endl;
	return 0;
}
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.