📘 Lesson · Lesson 73
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
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.