Reader small image

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

Product typeBook
Published inAug 2023
PublisherPackt
ISBN-139781804617830
Edition2nd Edition
Right arrow
Authors (5):
Marcelo Guerra Hahn
Marcelo Guerra Hahn
author image
Marcelo Guerra Hahn

Marcelo Guerra Hahn, With over 18 years of experience in software development and data analysis, Marcelo Guerra Hahn is a seasoned expert in C++, C#, and Azure. As an Engineering Manager at Microsoft C++ Team and former leader of SoundCommerce's engineering team, Marcelo's passion for data and informed decision-making shines through. He shares his knowledge as a lecturer at esteemed institutions like Lake Washington Institute of Technology and University of Washington. Through this book, Marcelo aims to empower readers with advanced C++ techniques, honed by real-world experience, to become proficient programmers and skilled data analysts.
Read more about Marcelo Guerra Hahn

Araks Tigranyan
Araks Tigranyan
author image
Araks Tigranyan

Araks Tigranyan is a passionate software engineer at Critical Techworks, with an unwavering love for the world of programming, particularly in C++. Her dedication to crafting efficient and innovative solutions reflects her genuine passion for coding. Committed to excellence and driven by curiosity, Araks continuously explores new technologies, going above and beyond to deliver exceptional work. Beyond programming, Araks finds solace in sports, with football holding a special place in her heart. As an author, Araks aspires to share her profound expertise in C++ and inspire readers to embark on their programming journeys.
Read more about Araks Tigranyan

John Asatryan
John Asatryan
author image
John Asatryan

John Asatryan, the Head of Code Republic Lab at Picsart Academy, seamlessly blends his academic background in International Economic Relations from the Armenian State University of Economics with his ventures in technology and education. Driven by a genuine passion for coding, John's commitment to empowering aspiring developers is evident in his expertise in the field. His unwavering dedication to bridging the gap between education and technology inspires others to pursue their coding dreams.
Read more about John Asatryan

Vardan Grigoryan
Vardan Grigoryan
author image
Vardan Grigoryan

Vardan Grigoryan is a senior backend engineer and C++ developer with more than 9 years of experience. Vardan started his career as a C++ developer and then moved to the world of server-side backend development. While being involved in designing scalable backend architectures, he always tries to incorporate the use of C++ in critical sections that require the fastest execution time. Vardan loves tackling computer systems and program structures on a deeper level. He believes that true excellence in programming can be achieved by means of a detailed analysis of existing solutions and by designing complex systems.
Read more about Vardan Grigoryan

Shunguang Wu
Shunguang Wu
author image
Shunguang Wu

Shunguang Wu is a senior professional staff at Johns Hopkins University Applied Physics Laboratory, and received his PhDs in theoretical physics and electrical engineering from Northwestern University (China) and Wright State University (USA), respectively. He published about 50 reviewed journal papers in the area of nonlinear dynamics, statistical signal processing and computer vision in his early career. His professional C++ experience started with teaching undergraduate courses in the late 1990s. Since then he has been designing and developing lots of R&D and end-user application software using C++ in world-class academic and industrial laboratories. These projects span both the Windows and Linux platforms.
Read more about Shunguang Wu

View More author details
Right arrow

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 2023Publisher: PacktISBN-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.
undefined
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 $15.99/month. Cancel anytime

Authors (5)

author image
Marcelo Guerra Hahn

Marcelo Guerra Hahn, With over 18 years of experience in software development and data analysis, Marcelo Guerra Hahn is a seasoned expert in C++, C#, and Azure. As an Engineering Manager at Microsoft C++ Team and former leader of SoundCommerce's engineering team, Marcelo's passion for data and informed decision-making shines through. He shares his knowledge as a lecturer at esteemed institutions like Lake Washington Institute of Technology and University of Washington. Through this book, Marcelo aims to empower readers with advanced C++ techniques, honed by real-world experience, to become proficient programmers and skilled data analysts.
Read more about Marcelo Guerra Hahn

author image
Araks Tigranyan

Araks Tigranyan is a passionate software engineer at Critical Techworks, with an unwavering love for the world of programming, particularly in C++. Her dedication to crafting efficient and innovative solutions reflects her genuine passion for coding. Committed to excellence and driven by curiosity, Araks continuously explores new technologies, going above and beyond to deliver exceptional work. Beyond programming, Araks finds solace in sports, with football holding a special place in her heart. As an author, Araks aspires to share her profound expertise in C++ and inspire readers to embark on their programming journeys.
Read more about Araks Tigranyan

author image
John Asatryan

John Asatryan, the Head of Code Republic Lab at Picsart Academy, seamlessly blends his academic background in International Economic Relations from the Armenian State University of Economics with his ventures in technology and education. Driven by a genuine passion for coding, John's commitment to empowering aspiring developers is evident in his expertise in the field. His unwavering dedication to bridging the gap between education and technology inspires others to pursue their coding dreams.
Read more about John Asatryan

author image
Vardan Grigoryan

Vardan Grigoryan is a senior backend engineer and C++ developer with more than 9 years of experience. Vardan started his career as a C++ developer and then moved to the world of server-side backend development. While being involved in designing scalable backend architectures, he always tries to incorporate the use of C++ in critical sections that require the fastest execution time. Vardan loves tackling computer systems and program structures on a deeper level. He believes that true excellence in programming can be achieved by means of a detailed analysis of existing solutions and by designing complex systems.
Read more about Vardan Grigoryan

author image
Shunguang Wu

Shunguang Wu is a senior professional staff at Johns Hopkins University Applied Physics Laboratory, and received his PhDs in theoretical physics and electrical engineering from Northwestern University (China) and Wright State University (USA), respectively. He published about 50 reviewed journal papers in the area of nonlinear dynamics, statistical signal processing and computer vision in his early career. His professional C++ experience started with teaching undergraduate courses in the late 1990s. Since then he has been designing and developing lots of R&D and end-user application software using C++ in world-class academic and industrial laboratories. These projects span both the Windows and Linux platforms.
Read more about Shunguang Wu