Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Expert C++ - Second Edition

You're reading from  Expert C++ - Second Edition

Product type Book
Published in Aug 2023
Publisher Packt
ISBN-13 9781804617830
Pages 604 pages
Edition 2nd Edition
Languages
Authors (5):
Marcelo Guerra Hahn Marcelo Guerra Hahn
Profile icon Marcelo Guerra Hahn
Araks Tigranyan Araks Tigranyan
Profile icon Araks Tigranyan
John Asatryan John Asatryan
Profile icon John Asatryan
Vardan Grigoryan Vardan Grigoryan
Profile icon Vardan Grigoryan
Shunguang Wu Shunguang Wu
Profile icon Shunguang Wu
View More author details

Table of Contents (24) Chapters

Preface 1. Part 1:Under the Hood of C++ Programming
2. Chapter 1: Building C++ Applications 3. Chapter 2: Beyond Object-Oriented Programming 4. Chapter 3: Understanding and Designing Templates 5. Chapter 4: Template Meta Programming 6. Chapter 5: Memory Management and Smart Pointers 7. Part 2: Designing Robust and Efficient Applications
8. Chapter 6: Digging into Data Structures and Algorithms in STL 9. Chapter 7: Advanced Data Structures 10. Chapter 8: Functional Programming 11. Chapter 9: Concurrency and Multithreading 12. Chapter 10: Designing Concurrent Data Structures 13. Chapter 11: Designing World-Ready Applications 14. Chapter 12: Incorporating Design Patterns in C++ Applications 15. Chapter 13: Networking and Security 16. Chapter 14: Debugging and Testing 17. Chapter 15: Large-Scale Application Design 18. Part 3:C++ in the AI World
19. Chapter 16: Understanding and Using C++ in Machine Learning Tasks 20. Chapter 17: Using C++ in Data Science 21. Chapter 18: Designing and Implementing a Data Analysis Framework 22. Index 23. Other Books You May Enjoy

Template Meta Programming

Template meta programming is a powerful technique in C++ that allows developers to write code that generates other code at compile time. This technique can be used to create highly efficient, generic, and reusable code, as well as to create domain-specific languages and other advanced features. In this book, you will learn the fundamentals of template metaprogramming and how to apply it to your own projects. You will also learn about the most important features of the C++ template system and the common pitfalls to avoid. Whether you are a beginner or an experienced C++ developer, this book will provide you with the knowledge and skills you need to master template metaprogramming and take your C++ programming to the next level.

In this chapter, we will discuss the following topics.

  • Programming at compile time – the fundamentals (compile-time programming with templates)
  • A Constexpr-based assessment of compile time
  • Substitution Failure...

Technical requirements

To learn and understand template metaprogramming, you should have a solid understanding of the C++ programming language, including experience with templates, classes, and functions. Familiarity with the Standard Template Library (STL) and generic programming is also helpful. Additionally, you should have a development environment set up with a C++ compiler that supports at least C++11, the version of the standard that introduced many of the features used in template metaprogramming. You can find the source files used in this chapter at https://github.com/PacktPublishing/Expert-C-2nd-edition.

Back to basics (compile-time programming with templates)

In the previous chapter, we discussed what templates are. In this chapter, we will go deeper into templates and will discuss why it is important to compute programs at compile time. In C++, there are some ways to compute values at compile time. New features have been added to language standards to carry out these functions.

The C++ template system is Turing-complete, meaning it has the ability to compute anything that can be computed, which was discovered during the process of standardizing the language. The first example of this was software that computed prime numbers, even though it did not complete compilation; the list of prime numbers was a component of the compiler’s error message. In essence, code determines whether a given number is a prime number at compile time.

Let us see the following example:

#include <iostream>template <size_t n>
class Foo
{
public:
    Foo(void ...

Compile-time evaluation using constexpr

The constexpr function was added in C++11 and enhanced in C++14. Besides the fact that we can declare a variable as constexpr, it indicates that, where possible, the return value is computed at compile time and is constant. A constexpr function is one whose return value can be computed at compile time when the consuming code requires it, according to the definition. In our example, the body of the function is written as a single statement because only a very small subset of the language can be used by constexpr functions. Many constexpr constraints were removed in C++14, making it much easier to write them now. You have already seen its use in the examples, and now, we will go deeper.

Here’s the syntax of constexpr:

  • constexpr literal identity = expression
  • constexpr literal identity {expression};
  • constexpr literal identity (parameters);
  • constexpr constructor (parameters);

As a constexpr variable, it must be...

SFINAE AND enable_if<>

Before C++17, there were already ways to enable or disable templates as a whole – a compile-time if, partial specialization, SFINAE, and enable_if<>. Referring to our previous example, is_prime<>, where we determined the authenticity of a prime number, we can use partial specialization to choose at compile time between different type implementations. We can choose different implementations depending on the argument (we used a struct in the code because function templates do not support partial specialization):

template <std::size_t n, bool = IsPrime(n)>class hash_table;
template <std::size_t n>
class hash_table<n, true>
{
public:
    std::array<int, n> bucket;
};
template <std::size_t n>
class hash_table<n, false>
{
public:
    array<int, next_prime<n>::value> bucket;
// next_prime<size_t n> is a meta function which compute
// the next prime...

Type traits

So far in this chapter, we can say that we have discussed only one technique of metaprogramming, which is called (as you already saw in its behavior) improved runtime performance. There is also a second approach, called improved type safety. If, with the first option, we could compute values at compile time, we can calculate the precise types required for algorithms or data structures in this section. Type features are a prime illustration of the second possibility. We can assess and alter types using a range of utilities called type traits, which are included in the Standard Library. This is also called the metaprogramming library. To use type traits, we must include the <type_traits> header:

Helper classes are the first category on the list:

  • integral_constant(C++11)
  • bool_constant(C++17)
  • true_type
  • false_type

As the root class for all C++ type traits is the std::integral constant, all standard type traits that produce values are descended...

Summary

Templates in C++ enable computation to occur during the build process. This means that certain operations, such as computing the factorial of a number, can be performed at compile time instead of runtime. While most compile-time calculations can be replaced with “ordinary functions” using constexpr functions, templates are still useful in cases where they are necessary. In template metaprogramming, it is possible to examine and even change the attributes of a type using type traits. One important concept in this field is SFINAE, which states that the replacement of functional templated declarations should not produce bad code, and templates should only be used when necessary. Another important aspect of templates is the constexpr if statement, which serves as a compile-time if statement. It allows for the conditional execution of statements based on constant expressions, enabling even more complex computations to occur during the build process. In summary, templates...

Questions

  1. What does metaprogramming actually entail?
  2. What was the first template metaprogramming program?
  3. When should you use constexpr?
  4. What is the difference between const and constexpr?
  5. Can a recursive function be constexpr?
  6. Implement a program that calculates the Fibonacci number at compile time.
lock icon The rest of the chapter is locked
You have been reading a chapter from
Expert C++ - Second Edition
Published in: Aug 2023 Publisher: Packt ISBN-13: 9781804617830
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}