Type-Traits Overview

In this lesson, we'll study the type traits library and its goals along with type-checks. This section could only provide an overview of the many functions of the type-traits library.

Type-Traits Library #

Type-traits enable type checks, type comparisons, and type modifications at compile-time.

Below are some applications of template metaprogramming:

  • Programming at compile-time
  • Programming with types and values
  • Compiler translates the templates and transforms it in C++ source code

We need to add a type_traits library in the header to enable all the functions present in the library.

#include <type_traits>

Type-Traits: Goals #

If you look carefully, you’ll see that type-traits have a significant optimization potential. In the first step, type-traits help to analyze the code at compile-time and in the second step, to optimize the code based on that analysis. How is that possible? Depending on the type of variable, a faster variant of an algorithm will be chosen.

Optimization #

  • Code that optimizes itself. Depending on the type of a variable another code will be chosen.
  • Optimized version of std::copy, std::fill, or std::equal is used so that algorithms can work on memory blocks.
  • The optimized version of operations happens on all the elements in a container in one step and not on each element individually.

Correctness #

  • Type checks will be performed at compile-time.
  • Type information, together with static_assert, defines the requirements for the code.
  • With the concepts in C++20, the correctness aspect of the type-traits becomes less important.

Type Checks #

C++ has 14 primary type categories. They are complete and orthogonal. This means, that each type is a member of exactly one type category. The check for the type categories is independent of the type qualifiers const or volatile.

Let’s have a look at these categories syntactically:

Create a free account to view this lesson.

Continue your learning journey with a 14-day free trial.

By signing up, you agree to Educative's Terms of Service and Privacy Policy