AnyCompiler

Templates

template <typename T> ek function ko us type ke saath kaam karne deta hai jo call site par decide hota hai, likhe jaane ke waqt nahi. Rust ke trait-bounded generics ke ulat, ek C++ template duck-typed hota hai: compiler ko bas itna chahiye ki jo operations aap actually function body ke andar use karte ho (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;
}
Output
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 use 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;
}
Output
42
hello

Aage: STL containers aur iterators — std::map, std::set, aur kisi bhi container ko same tarike se iterate karna.

Practice exercise

Ek template function first<T>(T a, T b) likho jo a return kare, phir first(10, 20) call karo aur result print karo.