Imagine writing maxInt, maxDouble, maxString... - the same logic copied for every type. Templates let you write the logic once with a placeholder type; the compiler generates the specific versions you use. This is generic programming, and the entire STL is built on it.
Function templates#
42 3.75 mango 7.5
template <typename T> introduces a type parameter T (class T means the same thing). From the arguments, the compiler deduces T and generates a real function - this is called instantiation.
Template एक साँचा (mould) है। आप logic एक बार लिखते हैं और type की जगह T रखते हैं। जब आप biggest(17, 42) लिखते हैं तो compiler खुद int वाला version बना देता है, biggest(3.75, 2.5) के लिए double वाला। एक code - अनगिनत types।
The template works for any type that supports the operations used inside it. biggest needs >, so it works for numbers, strings, and your own classes if they overload operator>.
Templates with arrays and several parameters#
72, 88, 65, 91 B, A, C, A 91 found at 3 Indore -> 452001 101 -> 8.75
Class templates#
A whole class can be generic too. This is how vector<T>, map<K, V> and pair<A, B> work:
10 Vindhyaedu true (CGPA, 9.2) (42, Z)
For class templates you usually write the type in angle brackets (Box<int>). Since C++17 the compiler can often deduce it from the constructor: Box b(10);.
Non-type template parameters#
A template parameter can also be a constant value, such as a size:
0 1 4 9 16 size = 5
std::array<int, 5> from the STL works exactly like this.
Template specialization#
Sometimes one type needs different behaviour. You can provide a specialized version for it:
a value: 42 a value: 3.500000 a string of length 9 true (bool)
Templates vs virtual functions#
| Templates | Virtual functions | |
|---|---|---|
| Polymorphism | compile-time | run-time |
| Speed | no run-time cost (code generated per type) | small cost per call |
| Mixing types in one container | no | yes (vector<Shape*>) |
| Error messages | can be long and confusing | simpler |
Summary#
template <typename T>writes a function or class once for any type; the compiler instantiates versions as needed.- Types are deduced from arguments, or given explicitly with
<type>. - Class templates power
vector,map,pair; non-type parameters give fixed sizes. - Specialize a template when one type needs special handling.