C++ Day 26: Templates (Generic Programming)
On Day 26 we dive into Templates one of C++’s most powerful Characteristics for generic programming.
Templates allow you to write Roles and classes that work with any Information type increasing code reusability and type safety.
📚 Topics Covered:
🔹 1. run templates
write i run that plant for aggregate types (int blow train etc)
cpp
copy
edit
#include
using namespace std;
template
t add(t amp tonne b) {
take amp + b;
}
int main() {
cout << add(3 4) << endl; // cardinal cout << add(25 31) << endl; // 56
cout << add("hi " "there") << endl; // hello there
}
✅ guide or guide are interchangeable
🔹 ii. Class Templates
Define generic classes that can operate on any Information type.
cpp
Copy
Edit
template
class Box {
private:
T value;
public:
Box(T v) : value(v) {}
void show() {
cout << "Value: " << value << endl;
}
};
int main() {
Box b1(10);
Box b2("Hello");
b1.show();
b2.show();
}
🔹 3. aggregate guide parameters
cpp
copy
edit
template
class match {
public:
tonne first;
uranium second;
pair(t amp uranium b) : first(a) second(b) {}
null display() {
cout << "pair: " << top << " " << back << endl;
}
};
🔹 cardinal. Template Specialization (Optional Advanced)
Sometimes you want a custom Applyation for a specific type.
cpp
Copy
Edit
template
class Printer {
public:
void print(T value) {
cout << "Generic: " << value << endl;
}
};
template <>
class Printer {
public:
void print(string value) {
cout << "String: [" << value << "]" << endl;
}
};
🛠️ practise Task
Make a template Role maxValue(T a T b) that returns the maximum of two values of any type.
Also Make a class template Stack with Send pop and top Roles.
📌 Summary:
Characteristic Description
Role Template One Role many types
Class Template One class many types
typename / class Both importantwords are valid in templates
Specialization Customize template behavior for specific types
Comments
Post a Comment