C++ Function Templates
C++ Function Templates
Function templates in C++ allow you to write generic functions that can operate on different data types. They provide a way to define a template for a function, and the compiler generates specific instances of the function for different types when called. Here's a basic example of a function template:
#include <iostream>
// Function template for swapping values
template <typename T>
void swapValues(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
std::cout << "Before swapping: x = " << x << ", y = " << y << std::endl;
// Call the function template with int types
swapValues(x, y);
std::cout << "After swapping: x = " << x << ", y = " << y << std::endl;
double a = 3.14, b = 6.28;
std::cout << "Before swapping: a = " << a << ", b = " << b << std::endl;
// Call the function template with double types
swapValues(a, b);
std::cout << "After swapping: a = " << a << ", b = " << b << std::endl;
return 0;
}
In this example, the swapValues function template uses the placeholder typename T to represent the generic type. The function can then be instantiated with specific types, such as int and double, when called in the main function.
Key points about function templates:
- Template Parameters: The template parameters (
typename T,class T, ortypename T1, typename T2, etc.) represent the generic types that the function can work with. These parameters can be any valid C++ identifier. - Instantiation: To call a function template, you need to provide the actual types for the template parameters. For example,
swapValues<int>(x, y)instantiates the function withinttypes. - Template Deduction: In many cases, the compiler can automatically deduce the template types based on the function arguments, so you don't always need to explicitly specify the types.
- Multiple Template Parameters: Function templates can have multiple template parameters. For example:
template <typename T1, typename T2>
T1 add(T1 a, T2 b) {
return a + static_cast<T1>(b);
}
This function template takes two different types (T1 and T2) and adds them, converting the second type to the first type.
Template Specialization:
You can provide template specializations for specific types. For example, if you want a specific behavior for a certain type, you can specialize the template:
// Template specialization for swapping char values
template <>
void swapValues<char>(char& a, char& b) {
// Specialized implementation for char
char temp = a;
a = b;
b = temp;
}
In this specialization, we provide a different implementation for the case when the type is char.
Function templates are widely used in C++ for creating generic algorithms and utility functions. They are an essential part of the C++ standard library and are used in many commonly used functions, such as those in containers like std::vector and algorithms like std::sort. Understanding function templates is crucial for writing flexible and reusable code.