What is the point in knowing whether an object is an integral or not or is a class type or not?

It's not for writing to the console, that's for sure.

More broadly you're asking: what is the point of type traits?

The answer is template metaprogramming. For example, I can create a template specialisation that does one thing for integral types, and another for non-integral types.

Aaron Bullman has a simple introduction to type traits, as does Jacek here.

In my opinion, most use of these things will be found buried within implementations of cool features and classes and utilities (i.e. in libraries) as part of the background machinery that makes it all work.

Further reading:

  • C++ Type Traits
  • How do traits classes work and what do they do?

rightfold's answer on that first one gives a superb example of when traits are useful:

For example, an implementation of std::copy may use std::memcpy internally instead of an explicit loop when the iterators are pointers to PODs. This can be achieved with SFINAE.


It's for template meta programming. When you have no idea what type(s) the end-user will pass into the template. Sometimes it's to report errors, sometimes it's to specialise on the types passed. Sometimes it's a combination.

The examples seen on cppreference.com (eg https://en.cppreference.com/w/cpp/types/is_enum ) are very much over simplified and just show how to use the trait in a non-typical manner. You would almost never use these traits directly in a simple (non-template function or class).

Tags:

C++

Templates