📘 Lesson · Lesson 73
Templates
Templates
What are Templates?
💡 Note
Templates let you write generic code that works with any data type — one function/class for int, double, string, etc.
Function Template
C++
#include <iostream>
using namespace std;
template <typename T>
T maximum(T a, T b) { return (a > b) ? a : b; }
int main() {
cout << maximum(3, 7) << "\n"; // 7
cout << maximum(2.5, 1.5) << "\n"; // 2.5
return 0;
}Output:
7 2.5
7 2.5
Summary
- Templates write type-independent code using
template <typename T>. - One template works for many data types.
Templates क्या हैं?
💡 Note
Templates आपको generic code लिखने देते हैं जो किसी भी data type के साथ चले — int, double, string आदि के लिए एक ही function/class।
Function Template
C++
#include <iostream>
using namespace std;
template <typename T>
T maximum(T a, T b) { return (a > b) ? a : b; }
int main() {
cout << maximum(3, 7) << "\n"; // 7
cout << maximum(2.5, 1.5) << "\n"; // 2.5
return 0;
}Output:
7 2.5
7 2.5
सारांश
- Templates
template <typename T>से type-independent code लिखते हैं। - एक template कई data types के लिए चलता है।