Templates
Iuliana
Bocicor
Code analysis
Templates Templates
C++
Standard
Template
Library
Iuliana Bocicor
[email protected]
Babes-Bolyai University
2025
1 / 26
Overview
Templates
Iuliana
Bocicor
Code analysis
Templates 1 Code analysis
C++
Standard
Template
Library
2 Templates
3 C++ Standard Template Library
2 / 26
Code analysis I
Templates
Iuliana Linter/Code analyser - an automated tool that analyses the
Bocicor
source code and signals programming errors, bugs, stylistic
Code analysis errors, suspicious code.
Templates
C++
Standard
They are used to help us improve our code.
Template
Library
Advantages:
Fewer errors in the final code (especially useful for industrial
applications, where fewer defects arrive in production).
Readable, maintainable, more consistent code, of better
quality.
Learning about best practices in writing modern C++ code.
For Visual Studio: Project → Properties → Code Analysis
→ Enable Code Analysis on Build
3 / 26
Code analysis II
Templates
We can select the sets of rules to be verified: Project →
Iuliana
Bocicor Properties → Code Analysis → Microsoft → Choose multi-
Code analysis
ple rule set: select all sets of rules starting with ”C++ Core”
Templates (for rules from C++ core Guidelines: https://isocpp.
C++ github.io/CppCoreGuidelines/CppCoreGuidelines).
Standard
Template
Library Code analysis will be made at compilation, warnings will be
reported in case guideline rules are broken.
See also: https://docs.microsoft.com/en-us/cpp/code-
using-the-cpp-core-guidelines-checkers?view=msvc-
For other platforms, you may use clang-tidy: http://
clang.llvm.org/extra/clang-tidy/.
4 / 26
Templates
Templates
Iuliana
Bocicor Generic programming - algorithms are written with generic
Code analysis
types, that are going to be specified later.
Templates
C++
Generic programming is supported by most modern pro-
Standard gramming languages.
Template
Library
In C++ templates allow working with generic types.
Provide a way to reuse source code. The code is written
once and can then be used with many types.
Allow defining a function or a class that operates on differ-
ent kinds of types (is parametrized with different types).
5 / 26
Function templates I
Templates
Iuliana Declaration
Bocicor
template <typename identifier> function declaration;
Code analysis
Templates
C++
template <typename T>
Standard T add (T a , T b )
Template
Library {
return a + b ;
}
T is the template parameter, a type argument for the tem-
plate;
The template parameter can be introduced with any of the
two keywords: typename, class.
6 / 26
Function templates II
Templates
Iuliana
Bocicor
The process of generating an actual function from a tem-
Code analysis
plate function is called instantiation:
Templates
C++
Standard
Template int r e s I n t = add<int >(3 , 4 ) ;
Library
double r e s D o u b l e = add<double >( −1.2 , 2 . 6 ) ;
DEMO
Function template. (Lecture 4 - FunctionTemplate.cpp).
7 / 26
Class templates I
Templates
Iuliana
Bocicor
A template can be seen as a skeleton or macro.
Code analysis
When specific types are added to this skeleton (e.g. double), then
Templates
the result is an actual C++ class.
C++ When instantiating a template, the compiler creates a new class
Standard
Template with the given template argument.
Library
The compiler needs to have access to the implementation of the
methods, to instantiate them with the template argument.
Place the definition of a template in a header file.
DEMO
Template (Lecture4 - DynamicVector.h, DynamicVector demo.cpp).
8 / 26
Class templates II
Templates
Iuliana Templates can be also defined for more types:
Bocicor
Code analysis template <typename T , typename U>
Templates class P a i r
C++ {
Standard
Template private :
Library
T first ;
U second ;
// ...
};
DEMO
Template (Lecture4 - Pair.h).
9 / 26
Templates - differences from void* implementation
Templates
Iuliana
Bocicor
Code analysis
Templates void* Template
C++ A container with void* A container can hold any type
Standard elements can only hold addresses. (both addresses and simple objects).
Template
Library Casting to a specific pointer is required, No casting needed.
in certain situations.
Memory management is required. Memory management is required
only in certain situations.
The container may include pointers All elements will have the same type.
to different types.
10 / 26
Templates - conclusions
Templates
Iuliana
Bocicor
Code analysis Templates are a compile-time mechanism.
Templates
C++
Standard
They are most commonly used in generic programming (im-
Template plementation of general algorithms).
Library
Useful for writing compact and efficient code.
The definition (not just the declaration) must be in scope
(usually in the header file).
11 / 26
Standard Template Library (STL)
Templates
Iuliana
Bocicor
Is a software library for C++.
Code analysis
Templates
Is a generic library, meaning that its components are heav-
C++
Standard ily parametrized: almost every component in the STL is a
Template
Library template.
Is designed such that programmers create components that
can be composed easily without losing any performance.
The primary designer and implementer of STL is Alexander
Alexandrovich Stepanov.
12 / 26
Containers in STL I
Templates
Iuliana
Bocicor
A container is a holder object that stores a collection of
Code analysis
other objects (its elements).
Templates
C++
Standard
Template
Containers are implemented as class templates.
Library
Containers:
manage the storage space for their elements;
provide member functions to access the elements, either
directly or through iterators (reference objects with similar
properties to pointers);
provide functions to modify the elements.
13 / 26
Containers in STL II
Templates
Container class templates:
Iuliana
Bocicor
Sequence containers (elements are ordered in a linear se-
Code analysis quence):
Templates array<T>;
C++ vector<T>;
Standard
Template deque<T>;
Library forward list<T>;
list<T>.
Associative containers (elements are referenced by their
keys and not by their absolute positions in the container):
set<T, CompareT>;
multiset<T, CompareT>;
map<KeyT,ValueT,CompareT>;
multimap<KeyT, ValueT,CompareT>.
14 / 26
Containers in STL III
Templates
Iuliana
Bocicor
Code analysis
Templates
Container adapters (created by limiting functionality in a
C++ pre-existing container):
Standard
Template
Library
stack<T, ContainerT>;
queue<T, ContainerT>;
priority queue<T,ContainerT, CompareT>.
15 / 26
Iterators I
Templates
Iuliana
Bocicor
Provide a generic (abstract) way to access the elements of
Code analysis
a container.
Templates
C++
Standard
Allow access to the elements of a container without expos-
Template
Library
ing the internal representation (implementation hiding).
Make a separation between how data is stored and how we
operate on data.
An iterator will contain:
a reference to the current element;
a reference to the container.
16 / 26
Iterators II
Templates
Iuliana
Bocicor
An iterator keeps track of a location within an associated STL
Code analysis container object, providing support for traversal (increment/decre-
Templates ment), dereferencing and container bounds detection.
C++
Standard
Template In C++, iterators are not pointers, but act similar to pointers
Library in certain situations (can be incremented with ++, dereferenced
with *, and compared against another iterator with !=).
Containers expose 2 member functions: begin() and end(), which
provide iterators towards the begin (first element) and the end
(past the last element) of the containers.
17 / 26
std::vector
Templates
Iuliana
Bocicor Is a container that stores elements of the same type.
Code analysis Is a sequence container: its elements are ordered in a linear
Templates sequence.
C++
Standard
Resizes automatically when needed.
Template
Library Uses a dynamically allocated array to store the elements.
Is very efficient in terms of element accessing (constant
time).
Works with range-based for loop.
DEMO
std::vector (Lecture4 - stl demo.cpp).
18 / 26
std::deque
Templates
Double ended queue, with dynamic size, that can be ex-
Iuliana
Bocicor panded or contracted at both ends.
Code analysis Elements are stored in chunks of storage, not in contiguous
Templates locations.
C++
Standard
Elements can be accessed through random access iterators.
Template
Library
Insertion and deletion of elements are efficient at both ends
(not just at the end, as in the case of vectors).
Deques are a little more complex internally than vectors, but
this allows them to grow more efficiently especially with very
long sequences, where re-allocations become more expen-
sive.
DEMO
std::vector (Lecture4 - stl demo.cpp).
19 / 26
std::list
Templates
Iuliana
Bocicor Implemented as a doubly linked list.
Code analysis Has constant time for inserting and erasing elements on any
Templates position.
C++
Standard Can be iterated in both directions.
Template
Library Compared to vectors and deques, lists perform better in
inserting, extracting and moving elements on positions for
which an iterator has already been obtained (thus also for
sorting algorithms).
DEMO
std::vector (Lecture4 - stl demo.cpp).
20 / 26
STL Algorithms I
Templates
Iuliana
Bocicor
Algorithms are function templates that can operate on ranges
Code analysis of elements, ranges defined by iterators.
Templates
C++
Standard
The iterators returned by the functions begin() and end()
Template of a container can be fed to an algorithm to enable using
Library
the algorithm with the container.
Iterators are the mechanism that make possible the decou-
pling of algorithms from containers.
Exempt us from writing the same functions (find, sort,
count) for different individual containers.
21 / 26
STL Algorithms II
Templates
Iuliana
Bocicor
Code analysis
Headers: <algorithm>, <numeric> - define a collection of
Templates
functions especially designed to be used on ranges of ele-
C++
Standard ments.
Template
Library
DEMO
STL Algorithms (Lecture4 - stl demo.cpp).
22 / 26
Lambda expressions I
Templates
Iuliana
Bocicor
Provide a mechanism to define anonymous functions (lo-
Code analysis
cally, within other functions).
Templates
C++
Standard The anonymous function is defined in the code where it is
Template
Library called.
Are very useful for certain algorithms of the STL (find if,
count if, transform, sort).
The return type of lambdas can be deduced, but it can also
be specified.
23 / 26
Lambda expressions II
Templates
Iuliana
Bocicor Syntax
Code analysis [capture list] (parameter list) {function body}
Templates [capture list] (parameter list) → return type {function body}
C++
Standard
Template
Library
E.g.
// ...
v e c t o r <int> oddNumbers ( 5 ) ;
c o p y i f ( i n t e g e r s . b e g i n ( ) , i n t e g e r s . end ( ) ,
oddNumbers . b e g i n ( ) , [ ] ( int x ) { return x % 2
== 1 ; } ) ;
24 / 26
Lambda expressions III
Templates
Iuliana
Bocicor
A lambda can store information about variables that are in
Code analysis the local block scope.
Templates
C++ The lambda function body can refer to those variables using
Standard
Template the same name as in the surrounding scope.
Library
This is possible using the capture list.
DEMO
STL Algorithms (Lecture4 - stl demo.cpp).
25 / 26
Advantages of STL algorithms
Templates
Iuliana
Bocicor simplicity: use existing code instead of writing the code
Code analysis
from scratch;
Templates
C++
correctness: known to be correct, tested;
Standard
Template
Library performance: generally perform better than hand written
code;
clarity: you can immediately tell that a call to sort sorts
the elements in a range;
maintainability: code is clearer and more straightforward
⇒ easier to write, read, enhance and maintain.
26 / 26