# C++ Templates

Nivå: advanced | Målgrupp: C++ programmerare | Förkunskaper: Stor vana att programmera i C++
https://www.ribomation.se/programmerings-kurser/cxx-templates/

Den här kursen lär dig allt du behöver veta för att inte längre tveka att skriva egna templates.
Efter kursen kan du designa implementera egna templates till hjälp för dina kolleger och den
organisation du jobbar för.

Det går knappast att skriva ett (icke-trivialt = seriöst) program i C++ utan att använda sig av
färdiga templates. Huvuddelen av standardbiblioteket i C++ bygger på templates, såsom STL
algorithms, iterators och containers. Emellertid, anses också templates vara komplicerat, framförallt
att skriva egna funktioner eller klasser med hjälp av templates. Och för all del, helt trivialt är
det ju inte.

Den här kursen lär dig allt du behöver veta för att inte längre tveka att skriva egna templates.
Efter kursen kan du designa implementera egna templates till hjälp för dina kolleger och den
organisation du jobbar för.

- Function templates
- Class templates
- Variable templates
- Variadic templated
- Fold expressions
- Non-type template parameters
- Template template parameters
- Perfect forwarding
- Template instantiation vs. specialization
- Argument deduction
- SFINAE
- Type traits
- C++20 concepts

#### Evolution of C++
Just a quick overview where C++ came from, its design criteria, evolution and finally,
how to compile it for the exercises of the course.

- Bjarne Stroustrup, inventor of C++
- C++ versions
- What is Modern C++
- Compiling a Modern C++ program
- Building a program using CMake
- Online compilers

#### Highlights of Modern C++
Essentials of the new standard, required to follow along in the course syllabus.

* Initialization syntax
* Initialization of STL containers
* Automatic type inference (auto)
* Using auto as return type of functions
* For-each loops
* Type aliases
* `decltype`
* `nullptr`
* `noexcept`
* Enforcing or deleting special members
* Lambda expressions
* Rvalue references (`T&&`)
* Move semantics
* Move special members

#### System Tools
Quick presentation of some tool-chain programs we are using during the course.

* Linux process address space organization, briefly
* How a stack-frame gets built
* `size`
* `nm`
* `objdump`
* `c++filt`
* Compiler Explorer
* C++ Insights

#### C++ Terminology
Short discussion of essential terms used in the standard and in this course, to avoid any conceptual confusions later.

- Declaration vs. definition
- West vs. east, regarding const, return and variables
- What is a translation unit, why does it matter
- The role of the compiler's symbol table
- Using `nm` to inspect the symbol table
- The one definition rule (ODR)
- Template entity naming

#### Before Templates
Brief about how developers did implement generic code before templates was invented in C++.

* What is generic code/programming
* Usage of CPP macros
* Writing a generic function, using CPP macro
* Instantiating and using a generic function
* Writing a generic type, using CPP macro
* Instantiating several type variants and using a generic type

#### Function Templates
How to write function templates.

- The problem of not having function templates
- Function template syntax
- What is the compiler actually generating
- Let the compiler figure out the type
- Let the compiler show you the type
- What is type equivalence and why you need to understand it
- What happens if an operator or function is not supported
- Usage of `typename`
- Example of implementing some functions from STL
- Partial vs. full instantiation of a function template
- Template parameters with default types

#### Class Templates
How to write class templates.

- The problem of not having class templates
- Class template syntax
- What is the compiler actually generating
- Type equivalence for class templates
- Writing methods outside the class and the syntax
- Example code
- Subclasses and templates
- The problem with inherited methods and how to fix it
- Static member variables in class templates
- Inline static variables in C++17
- Generic instance counts
- The Curiously Recurring Template Pattern (CRTP)

#### Non-Type Template Parameters (NTTP)
Templates parameters can be lots of other things, besides of plain types. Here we discuss the all.

- Value template parameters
- Using auto for value parameters
- Example code
- Prefer east return
- How to pass a native string (aka C string) as a template argument
- Template member functions (TMF)
- Writing TMF outside its class
- Template template parameters (TTP)
- Syntax for TTP
- Example code of TTP

#### Variable Templates and `constexpr`
Since C++14 we can make read-only variables as template, which means the actual type can be determined at
instantiation time. In this chapter we also discuss compile-time functions (`constexpr`) and C++17 `if constexpr` statements.

- Compile-time values
- Compile-time functions
- Example code
- Variable templates and why we might need them
- Recursive variable template
- Compile-time assertions
- Simple type predicates
- Compile-time `if` statements and why it is really useful

#### Variadic Templates
Templates can be declared with an unspecified number of parameters. In this chapter we show you how
to deal with parameter and argument packs, as well as fold expressions.

- What is a variadic template
- Simple variadic function template
- The `sizeof...` operator
- Variadic member function template
- Implementing an emplacement member
- Fold expressions in C++17
- Syntax for all fold expression variants
- Example code
- Implementation of class `Record<T...>` (similar to std::tuple)

#### Template Specialization
How to write special versions of a template entity.

- What is a specialization
- Example code of a type-dependent equals function
- Specialization of a variable template
- Type-dependent values
- Specialization of a class template
- Partial vs. full specialization
- Example code of linked-list container type

#### Template Instantiation
Discussion of how the compiler decides of what code to generate. What we mean in more detail with
instantiation and specialization.

- Template specialization - more formally
- Template instantiation vs. OOP instantiation
- Implicit instantiation
- Explicit instantiation
- Explicit specialization
- The bigger picture of what we just discussed
- How the compiler and linker collaborates
- Cfront, greedy and queried instantiation

#### Argument Deduction
How the compiler performs pattern matching in order to figure out the actual types of a template invocation.

- Two-phase translation of templates
- Two-phase name lookup
- Dependent types
- Understanding the challenges of parsing template code
- The importance of prefixing dependent types with `typename`
- Understanding overload resolution
- Why you should avoid specialize function templates
- How you can implement specialized functions safely
- Template argument deduction (TAD)
- TAD initial scenario
- TAD pattern matching challenge
- Boost type-index library
- Type deduction for _pass-by-value_
- Type deduction for _pass-by-reference_
- Type deduction for _pass-by-forwarding-reference_
- Universal reference
- Recap of lvalue and rvalue
- About xvalue, prvalue and glvalue
- Understanding `std::move`
- Understanding `std::forward`
- Implementing _perfect forwarding_
- Writing a variadic function template with perfect forwarding

#### Programming with Types
In this chapter we step-by-step implements a generic print function, that uses type-dependent print strategies.

- Use cases
- Start with a baseline
- Supporting pointers and print what's pointed on
- Printing boolean values
- Printing floating-point values
- Printing the elements of a static array
- Printing a C string, which might come in several forms
- Printing the elements of a dynamic array, using a `span` object
- Printing the elements of an STL container
- Printing the elements of an STL associative container
- Printing the elements of an STL map container
- Printing the elements of an STL array

#### Type Traits
The standard library contains many utility functions for manipulating with types in template entities, such
as type predicates, type transformers and type inspectors. In this chapter we first show how to implement
some of them to understand how it works, then we present some of them in `<type_traits>`.

- Type predicates
- Type transforms
- Using `std::type_traits`
- Inspecting the source code of `std::type_traits`
- Overview of the contents in `std::type_traits`
- Understanding `std::decay<T>`
- Understanding `std::conditional<T...>`
- Example: populating a vector with numeric random-generated values

#### SFINAE
The acronym SFINAE, which means Substitution Failure Is Not An Error, is an essential part of the toolbox
when implementing meta-functions.

- Function (template) overload resolution
- Example: getting the size of "something"
- Deduction is based on the function signature
- How to check if a template argument object has a specific member function
- Understanding SFINAE
- Using `std::enable_if<E, T>`
- Example: writing constructors for initializing a container
- Inflating with the same value
- Inflating with a iterator range
- Iterator traits and tags
- Understanding and using `std::void_t<T...>`
- Unit tests of type-requirements
- Understanding and using `std::declval<T>`
- Meta-functions

#### C++20 Concepts
With concepts in C++20, we can write generic functions much easier and safely. The compiler can also
much better tell us what is wrong when we use it wrongly. This is because with concepts we specify
the criteria of the allows argument types to a function or member function.

- What is a concept
- C++17 vs. C++20 regarding type-requirements
- Looking at error messages from failed concepts
- Overview of `std::concepts`
- Syntax for a `concept` definition
- Example: `concept is_numeric<T>`
- Syntax for a `requires` clause
- Placement of requires clause at function templates
- Constrained template parameter
- Abbreviate function template (aka annotated auto)
- Usage of concepts with class templates
- Usage of concepts with member functions
