C++ Templates - A Beginner's Tutorial
C++ templates are a powerful feature that allows you to write generic functions and classes. They provide a way to create code that can work with different data types while maintaining type safety. In this guide, we'll explore the basics of C++ templates.
Function Templates
A function template allows you to define a generic function that can work with multiple data types. Here's the basic syntax:
template <class T>
T add(T a, T b) {
return a + b;
}
Example:
#include <iostream>
using namespace std;
template <class T>
T add(T a, T b) {
return a + b;
}
int main() {
int result1 = add(5, 3);
double result2 = add(2.5, 1.2);
cout << "Result 1: " << result1 << endl;
cout << "Result 2: " << result2 << endl;
return 0;
}
In this example, the add
function template can add two integers or two floating-point numbers, and it's instantiated with the appropriate data types based on the arguments.
Class Templates
A class template allows you to create generic classes that can work with different data types. Here's the basic syntax:
template <class T>
class Pair {
public:
T first;
T second;
Pair(T a, T b) : first(a), second(b) {}
};
Example:
#include <iostream>
using namespace std;
template <class T>
class Pair {
public:
T first;
T second;
Pair(T a, T b) : first(a), second(b) {}
};
int main() {
Pair<int> intPair(5, 10);
Pair<double> doublePair(2.5, 1.2);
cout << "Integer Pair: " << intPair.first << ", " << intPair.second << endl;
cout << "Double Pair: " << doublePair.first << ", " << doublePair.second << endl;
return 0;
}
In this example, the Pair
class template can create pairs of integers or pairs of floating-point numbers, and it's instantiated with the appropriate data types.
Conclusion
C++ templates are a versatile tool for writing generic and reusable code. They allow you to write functions and classes that can work with different data types, promoting code reusability and type safety. As you continue your C++ journey, you'll explore more advanced template features and best practices.