Type Traits

Learn how to use type traits to categorize data types.

When doing template metaprogramming, we may often find ourself in situations where we need information about the types we are dealing with at compile time. When writing regular (non-generic) C++ code, we work with concrete types that we have complete knowledge about, but this is not the case when writing a template; the concrete types are not determined until the compiler is instantiating a template. Type traits let us extract information about the types our templates are dealing with to generate efficient and correct C++ code.

In order to extract information about template types, the standard library provides a type traits library, which is available in the <type_traits> header. All type traits are evaluated at compile time.

Type trait categories

There are two categories of type traits:

  • Type traits that return information about a type as a boolean or an integer value.
  • Type traits that return a new type. These type traits are also called metafunctions.

The first category returns true or false, depending on the input, and ends with _v (short for value).

Note: The _v postfix was added in C++17. If the library implementation does not provide _v postfixes for type traits, then we can use the older version, std::is_floating_point<float>::value. In other words, remove the _v extension and add ::value at the end.

Here are some examples of compile-time type checking using type traits for fundamental types:

Get hands-on with 1200+ tech skills courses.