Logo

Notebook C++: Tips and Tricks with Templates


Foreword

One of the problems that C++ programmers face using templates is understanding the complex syntax. Mastering Templates can be a game-changer when programming C++, as it is a powerful feature for writing clean code.

In this book from the Notebook C++ series, I show you tips and tricks on how to write templates efficiently. It starts with the basics, like the different template parameter types and techniques like always_false. You’ll then learn more about best practices. For example, where to put the enable_if and how to disable a special member function.

Notebook C++: Tips and Tricks with Templates is a quick-reference book where you can find the information the moment you need it for programming.

Stuttgart, February 2024

Andreas Fertig

Table of Contents

  • Notes by Standard at a Glance
    • Notes belonging to C++11
    • Notes belonging to C++17
    • Notes belonging to C++20
  • 1 Tips and Tricks with Templates
    • Note 1 : Know the name
    • Note 2 : Templates can have type and non-type parameters
    • Note 3 : When to use typename and when to use class
    • Note 4 : The elements of a variadic template
    • Note 5 : There are no implicit conversions for template parameters
    • Note 6 : Alias template for clean TMP
    • Note 7 : Variable templates for clean TMP
    • Note 8 : Using trailing return type syntax with decltype and void()
    • Note 9 : Use declval when you need to construct a type for testing during compile-time
    • Note 10 : What void_t does
    • Note 11 : Keep that array's size
    • Note 12 : There is no else if in C++
    • Note 13 : More useful than it appears: always_false
    • Note 14 : Prefer auto as an NTTP to reduce redundancy
    • Note 15 : Block template argument deduction
    • Note 16 : Fold expressions and the comma operator
    • Note 17 : A Poor Man's Fold Expression
    • Note 18 : From an array to a pack
    • Note 19 : From an array to a pack with templated lambda
    • Note 20 : Create objects in place for direct use
    • Note 21 : Guidelines for efficient use of templates
    • Note 22 : Put enable_if on the return type
    • Note 23 : enable_if and how to disable a member function
    • Note 24 : How to disable a special member function
  • Acronyms
  • Bibliography
  • Index

Extract

Table of Contents[ pdf ]

Errata

I'm always interested in issue reports or suggestions for improvements.

I like to thank every reader who pointed errors out.

First edition

Location
Correction
Note 23.3
The example needs to take the `Dummy` parameter in the `enable_if` (which should be `enable_if_t`) and default `Dummy` to the expected return type.