⚡0 XP🔥0

Templates

Lesson 9 of 12 ⏱ 6 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs C++

Write generic code once for any type - function templates, class templates, multiple type parameters, non-type parameters and template specialization.

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#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
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#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
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:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
10 Vindhyaedu
true
(CGPA, 9.2)
(42, Z)
Note

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:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
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:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
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.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Generic array sum

Write template <typename T> T sumAll(const vector<T> &v) and use it for ints and doubles:

Sum of ints: 15
Sum of doubles: 7.5
Expected output:
Sum of ints: 15
Sum of doubles: 7.5
2

A generic Stack class

Write template <typename T> class Stack with push, pop (returns the top and removes it), top, empty and size, using a vector<T> inside. The given main must print:

Size: 3
Top: 30
Popped: 30 20
Strings: C++ then Java
Expected output:
Size: 3
Top: 30
Popped: 30 20
Strings: C++ then Java

Quick Quiz

Q1.

What is a template?

Q2.

Given template <typename T> T biggest(T a, T b), what does biggest(3, 7.5) do?

Q3.

The STL vector is an example of...

Q4.

When are template errors reported?