Sections[temp]
Templates
Generic code from the first function template to concepts and compile-time programming, for developers who use templates daily and still fear them a little.
- Clause
- 3 of 8
- Answers
- 3, newest first
- Written for
- C++20
- Written by
- Miriam Castellanos
Templates write code once for many types, and turn a one-character mistake into a page of errors. Since C++20, concepts let a template state what it needs in its declaration. This section covers writing generic code, constraining it, computing at compile time, reading the errors and keeping builds quick. Start with generic lambdas, template lambdas and function objects, then strings as template parameters with C++20 fixed_string and expression templates, which run a + b + c in one loop with no temporaries.
In this section
- Function and class templates
- Concepts and constraints
- Template argument deduction
- Variadic templates and fold expressions
- Compile-time programming with
constexpr - Compile-time strings and non-type template parameters
- Type traits and what replaced SFINAE
- Expression templates and embedded DSLs
- Reading template error messages
- Generic lambdas and function objects
- Static reflection
- Compile times
Answers in Templates 3, newest first
C++ expression templates explained with a C++20 example
Build a C++20 expression template that runs a + b + c in one loop with no temporaries, count what it removes, and see when Eigen or ranges fit better.
written for C++20
Strings as C++ template parameters with C++20
fixed_stringA string literal can’t be the argument of a pointer template parameter. How a C++20
fixed_stringtype fixes that, what came before, and what C++26 adds.written for C++20
C++ generic lambdas, template lambdas and function objects
Write generic lambdas with auto (C++14) and template parameter lists (C++20), and know when a function template or a named function object is the better tool.
written for C++20