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.
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.
- Code that optimizes itself. Depending on the type of a variable another code will be chosen.
- Optimized version of
std::equalis 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.
- 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.
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
Let’s have a look at these categories syntactically: