C++ Templates
Templates in C++ allow you to write generic and reusable code for functions and classes. With templates, you can create a single function or class to work with different data types without rewriting code for each type. Templates are a key feature of generic programming in C++.
Types of Templates
- Templates allow code reuse and type safety without duplicating code for each data type.
- Function templates are useful for generic functions like sorting, swapping, or finding max/min values.
- Class templates are commonly used in the Standard Template Library (STL) containers like
vector,list, andmap.
Next Topic
Next, learn about Exception Handling in C++.
- Function Templates: Allow a single function to operate with different data types.
- Class Templates: Allow a single class to work with different data types.
Example: Function Template
#include <iostream>
using namespace std;
// Function template to find the maximum of two values
template <typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << "Max of 5 and 10: " << getMax(5, 10) << endl;
cout << "Max of 3.5 and 2.8: " << getMax(3.5, 2.8) << endl;
cout << "Max of 'A' and 'Z': " << getMax('A', 'Z') << endl;
return 0;
}
Output
Max of 5 and 10: 10 Max of 3.5 and 2.8: 3.5 Max of 'A' and 'Z': Z
Example: Class Template
#include <iostream>
using namespace std;
// Class template
template <typename T>
class Box {
private:
T content;
public:
void setContent(T c) {
content = c;
}
T getContent() {
return content;
}
};
int main() {
Box<int> intBox;
intBox.setContent(123);
cout << "Integer Box: " << intBox.getContent() << endl;
Box<string> strBox;
strBox.setContent("Hello");
cout << "String Box: " << strBox.getContent() << endl;
return 0;
}
Output
Integer Box: 123 String Box: Hello
Important Notes
- Templates allow code reuse and type safety without duplicating code for each data type.
- Function templates are useful for generic functions like sorting, swapping, or finding max/min values.
- Class templates are commonly used in the Standard Template Library (STL) containers like
vector,list, andmap.
Next Topic
Next, learn about Exception Handling in C++.