Understanding and Defining Type Traits
Learn the concept of type traits and how they are used in template metaprogramming.
We'll cover the following...
In a nutshell, type traits are small class templates that contain a constant value whose value represents the answer to a question we ask about a type. An example of such a question is, Is this type a floating-point type? The technique for building type traits that provide such information about types relies on template specialization; we define a primary template as well as one or more specializations.
Let’s see how we can build a type trait that tells us, at compile-time, whether a type is a floating-point type:
template<typename T>struct is_floating_point{static const bool value = false;};template<>struct is_floating_point<float>{static const bool value = true;};template<>struct is_floating_point<double>{static const bool value = true;};template<>struct is_floating_point<long double>{static const bool value = true;};
There are two things to notice here:
We have defined a primary template as well as several full specializations, one for each type that is a floating-point type.
The primary template has a
static const
boolean member initialized with thefalse
value; the full specializations set the value of this member totrue
.
There is nothing more to building a type trait than this. The is_floating_point<T>
type trait tells us whether a type is a ...