Templates
template <typename T> ek function ko us type ke sath kaam karne deta hai jo call site par decide hota hai, likhe jaane ke waqt nahi. Rust ke trait-bounded generics ke bar-aks, ek C++ template duck-typed hota hai: compiler ko bas itna chahiye ke jo operations aap actually function body ke andar istemal karte hain (yahan, > aur copying) woh jo bhi T ho uske liye valid hon.
#include <iostream>
using namespace std;
template <typename T>
T maxOf(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << maxOf(3, 7) << endl;
cout << maxOf(2.5, 1.5) << endl;
return 0;
}7 2.5
Class templates
Ek class bhi templated ho sakta hai — neeche Box<T> kisi bhi type T ke liye kaam karta hai, jahan bhi class istemal hota hai wahan specific type fill ho jaata hai, jaise Box<int> ya Box<string>.
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class Box {
private:
T value;
public:
Box(T v) : value(v) {}
T getValue() const {
return value;
}
};
int main() {
Box<int> intBox(42);
Box<string> strBox("hello");
cout << intBox.getValue() << endl;
cout << strBox.getValue() << endl;
return 0;
}42 hello
Aage: STL containers aur iterators — std::map, std::set, aur kisi bhi container ko same tareeqe se iterate karna.
Practice exercise
Ek template function first<T>(T a, T b) likhein jo a wapas kare, phir first(10, 20) call karein aur result print karein.