Function templates in C++ allow you to define functions that can operate with any data type. Instead of writing multiple functions for different data types, you can write a single function template that works for all types.
template
keyword signals the start of a function template definition.<>
) to represent data types that the function can work with. These placeholders are typically named using uppercase letters like T
.Function templates in C++ allow you to write generic functions that can operate with any data type. This section covers the basic syntax and usage of function templates.
#include
template
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
std::cout << "Maximum of 5 and 10 is: " << max(5, 10) << std::endl;
std::cout << "Maximum of 3.5 and 2.8 is: " << max(3.5, 2.8) << std::endl;
return 0;
}
max
using the template <typename T>
syntax.typename T
declares T
as a template parameter, representing the data type of the arguments and return type of the function.T
to represent the data type of the arguments and perform comparison operations.Function Template Usage
main()
function, we call the max
function template with different data types (int
and double
) without needing to define separate functions.T
based on the arguments provided during function calls.
// output //
Maximum of 5 and 10 is: 10
Maximum of 3.5 and 2.8 is: 3.5
In this section, we explore advanced techniques for designing and using function templates in C++. These techniques include function template specialization, default template arguments, and variadic templates.
Function template specialization allows you to provide a customized implementation for specific template arguments.
#include
template
T max(T a, T b) {
std::cout << "Generic max() called" << std::endl;
return (a > b) ? a : b;
}
template <>
const char* max(const char* a, const char* b) {
std::cout << "Specialized max() called" << std::endl;
return strcmp(a, b) > 0 ? a : b;
}
int main() {
std::cout << "Maximum of 'apple' and 'banana' is: " << max("apple", "banana") << std::endl;
return 0;
}
// output //
Specialized max() called
Maximum of 'apple' and 'banana' is: banana
max
function template for the const char*
data type to provide a customized implementation.max
compares C-style strings using strcmp
.main()
function, when we call max
with two C-style strings, the specialized version of max
is called.You can provide default template arguments for function templates, allowing the template to be used with fewer template arguments.
#include
template
T add(T a, T b) {
return a + b;
}
int main() {
std::cout << "Sum of 5 and 10 is: " << add(5, 10) << std::endl; // Uses int
std::cout << "Sum of 3.5 and 2.8 is: " << add(3.5, 2.8) << std::endl; // Uses double
return 0;
}
// output //
Sum of 5 and 10 is: 15
Sum of 3.5 and 2.8 is: 6.3
add
function template has a default template argument of int
.add(5, 10)
without specifying the template argument, the function template is instantiated with T = int
.add<double>(3.5, 2.8)
, which instantiates the function template with T = double
.Variadic templates allow function templates to accept an arbitrary number of arguments.
#include
template
T sum(T value) {
return value;
}
template
T sum(T first, Args... rest) {
return first + sum(rest...);
}
int main() {
std::cout << "Sum of 1, 2, 3, and 4 is: " << sum(1, 2, 3, 4) << std::endl;
return 0;
}
// output //
Sum of 1, 2, 3, and 4 is: 10
sum
that recursively adds all its arguments.sum
that takes a single argument and returns it.sum
with the remaining arguments.This code defines a swap
function template that swaps two values of type T
. In the main
function, it demonstrates swapping integers (int
) and swapping floating-point numbers (double
).
#include
template
void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
double d1 = 3.14, d2 = 2.72;
std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;
swap(x, y); // Template argument: int
std::cout << "After swap: x = " << x << ", y = " << y << std::endl;
std::cout << "Before swap: d1 = " << d1 << ", d2 = " << d2 << std::endl;
swap(d1, d2); // Template argument: double
std::cout << "After swap: d1 = " << d1 << ", d2 = " << d2 << std::endl;
return 0;
}
// output //
Before swap: x = 5, y = 10
After swap: x = 10, y = 5
Before swap: d1 = 3.14, d2 = 2.72
After swap: d1 = 2.72, d2 = 3.14
swap
is a function template that takes two references of type T
and swaps their values.main
function:x
and y
are initialized with values 5 and 10 respectively.d1
and d2
are initialized with values 3.14 and 2.72 respectively.x
and y
are printed before and after swapping.d1
and d2
are printed before and after swapping.You can have multiple template parameters to create functions that work with a combination of data types.
#include
template
void printPair(const T& t, const U& u) {
std::cout << "Element 1: " << t << ", Element 2: " << u << std::endl;
}
int main() {
int x = 5;
double d = 3.14;
std::string str = "Hello";
printPair(x, d); // Template arguments: int, double
printPair(d, str); // Template arguments: double, string
return 0;
}
// output //
Element 1: 5, Element 2: 3.14
Element 1: 3.14, Element 2: Hello
printPair
function template takes two parameters of types T
and U
, and it prints both parameters.main
function:x
, a double d
, and a string str
are declared and initialized with values.printPair
function is called twice:Summary: Function templates in C++ are powerful tools for writing generic functions that operate with any data type. They promote code reuse, flexibility, and simplicity by allowing you to write functions that work with multiple data types.
Importance: Understanding function templates is essential for writing generic and reusable code in C++. By mastering function templates, programmers can write more flexible and maintainable code that adapts to different data types without sacrificing performance or clarity.
Function templates are a cornerstone of modern C++ programming. By leveraging function templates effectively, developers can write more efficient and flexible code that meets the diverse requirements of complex software systems.Happy coding !❤️