12 C++ conceptual art: Templates and concepts

 

This chapter covers

  • Diving deep into the concept of template
  • Understanding template specialization
  • Exploring templates and the concept of metaprogramming
  • Unraveling the C++20 concepts and constraints

In this chapter, we will explore the powerful features that allow you to write generic code and express powerful constraints on types: templates and concepts. Throughout this chapter, you will learn how to write generic code using templates.

You will learn that templates are not just limited to generic programming but open the door to a realm of advanced techniques and metaprogramming, where you can harness the full power of the C++ language to manipulate types, and perform computations at compile time. These techniques, such as template specialization, and template metaprogramming, provide us with the ability to craft highly optimized and specialized code – and in this chapter, we explore them all.

We then move and explore various techniques to effectively apply constraints using concepts – a new and highly anticipated addition to the C++ language, added in C++20. We will cover different ways to use concepts, including the requires clause, trailing requires clause, abbreviated function templates, and constrained template parameters, and learn how to use concepts with functions and class templates.

12.1 Templates – C++ “plug and play” components

12.1.1 It’s classic: The power of class template

12.1.2 Templates and polymorphism

12.1.3 The non-issue non-type template parameters

12.1.4 Template metaprogramming: it all started by accident

12.1.5 Houston, we have a substitute failure

12.1.6 ::value and ::type: The quirky twins of template metaprogramming

12.1 A brilliant concept: C++ Concepts and Constraints

12.1.1 Inside the concept of concepts

12.1.2 Meet C++ new keywords: ‘requires’ and ‘concept’

12.1.3 Conceptual art: Concepts hands on

12.1.4 Functions dancing to the beat of concepts

12.1.5 A Tale of Two Clauses: Concepts and classes

12.2 Final exercise

12.3 Summary