C++ Templates Tutorial
C++ templates allow you to write generic and reusable code that works with different data types. Templates provide type safety while maintaining flexibility.
Function Templates
Function templates are used to create a single function that operates on different data types:
#include <iostream>
using namespace std;
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << add(3, 4) << endl; // Integer addition
cout << add(3.5, 4.5) << endl; // Floating-point addition
return 0;
}
Class Templates
Class templates are used to define generic classes:
#include <iostream>
using namespace std;
template <typename T>
class Box {
private:
T value;
public:
Box(T val) : value(val) {}
T getValue() { return value; }
};
int main() {
Box<int> intBox(42);
Box<string> strBox("Template");
cout << intBox.getValue() << endl;
cout << strBox.getValue() << endl;
return 0;
}
Template Specialization
You can create specialized versions of templates for specific data types:
#include <iostream>
using namespace std;
template <typename T>
class Box {
public:
void print() { cout << "Generic template" << endl; }
};
template ><
class Box<int> {
public:
void print() { cout << "Specialized for int" << endl; }
};
int main() {
Box<int> intBox;
Box<float> floatBox;
intBox.print();
floatBox.print();
return 0;
}
Advantages of Templates
- Code reusability for different data types.
- Type safety with compile-time checks.
×