What are Templates?
Templates allow you to create functions or classes that work with any data type. Instead of writing the same code for different data types, templates enable you to write generic, reusable code.
Types of Templates
- Function Templates: Generic functions that work with any data type.
- Class Templates: Generic classes that can operate on different data types.
Function Template Example
#include <iostream> using namespace std; template <typename T> T getMax(T a, T b) { return (a > b) ? a : b; } int main() { cout << "Max of 10 and 20: " << getMax(10, 20) << endl; cout << "Max of 3.5 and 2.1: " << getMax(3.5, 2.1) << endl; cout << "Max of 'a' and 'z': " << getMax('a', 'z') << endl; return 0; }
The getMax
function works for int
, double
, and char
because of the template.
Class Template Example
#include <iostream> using namespace std; template <class T> class Calculator { T num1, num2; public: Calculator(T a, T b) : num1(a), num2(b) {} T add() { return num1 + num2; } }; int main() { Calculator<int> intCalc(5, 10); cout << "Sum (int): " << intCalc.add() << endl; Calculator<double> doubleCalc(4.5, 3.1); cout << "Sum (double): " << doubleCalc.add() << endl; return 0; }
Key Takeaways
- Templates enable code reuse and type safety.
- They reduce code duplication for similar operations.
- Both
typename
andclass
keywords are used to declare template parameters. - Function templates and class templates can be overloaded and specialized.