📘 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.
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
सारांश
- Templates write type-independent code using
template <typename T>. - One template works for many data types.
💻 Live Code Editor
Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें.
Agar load na ho to naye tab mein kholें.