C++ Class Templates
C++ Class Templates
Class templates in C++ allow you to create generic classes that can work with different data types. They provide a way to define a template for a class, and you can then instantiate objects of that class with different types. Here's a basic example of a class template:
#include <iostream>
// Class template for a generic Pair
template <typename T1, typename T2>
class Pair {
public:
T1 first;
T2 second;
// Constructor
Pair(const T1& f, const T2& s) : first(f), second(s) {}
// Member function to display the pair
void displayPair() const {
std::cout << "(" << first << ", " << second << ")" << std::endl;
}
};
int main() {
// Instantiate objects of Pair with different types
Pair<int, double> myPair1(5, 3.14);
Pair<std::string, char> myPair2("Hello", 'A');
// Display the pairs
myPair1.displayPair();
myPair2.displayPair();
return 0;
}
In this example, the Pair class template takes two template parameters (T1 and T2) representing the types of the first and second elements of the pair. Objects of the Pair class can be instantiated with different types, such as <int, double> and <std::string, char>.
Key points about class templates:
- Template Parameters: The template parameters (
T1,T2, etc.) are used to represent the generic types. These parameters can be any valid C++ identifier. - Instantiation: To create an object of a class template, you need to provide the actual types for the template parameters. For example,
Pair<int, double>instantiates thePairclass withintanddoubletypes. - Member Functions: Member functions of a class template can use the template parameters, just like member variables. These functions can be defined within the class template or separately.
- Const-Correctness: It's a good practice to use
constappropriately to ensure const-correctness. In the example, thedisplayPairfunction is marked asconstsince it doesn't modify the object.
Template Specialization:
You can also provide template specializations for specific types. For example, if you want a specific behavior for a certain type, you can specialize the template:
template <>
class Pair<std::string, char> {
public:
std::string first;
char second;
Pair(const std::string& f, char s) : first(f), second(s) {}
void displayPair() const {
std::cout << "Specialized Pair: (" << first << ", " << second << ")" << std::endl;
}
};
In this specialization, we provide a different implementation for the case when the first type is std::string and the second type is char.
Class templates provide a powerful way to write generic code in C++. They are commonly used in the C++ standard library for container classes like std::vector, std::map, etc. Understanding class templates is crucial for building flexible and reusable code.