Introduction to Type Traits in the C++ standard library
Yvonne Ma 270003Y3PJ Visits (29896)
The origin of Type Traits can be traced back to the TR1 and boost libraries. However, the Type Traits feature is formally introduced into the C++ language in the C++11 standard library. As its name suggests, Type Traits exposes different characteristics of types, or simply the “type of type”. In many C++ programming practices, especially these in template metaprogramming, developers may find it difficult to build a template work for all types without knowing the characteristics of a type. That’s the key reason for the emergence of Type Trait.
In the book “Understanding C++11”, for instance, we used Type Traits to analyze the characteristics of types.
Note that the function is_pod is declared as constexpr, which is another famous feature in C++11 that can evaluate expression at compile time. The return value of is_pod is actually evaluated to true(1). So the main function in the previous example is equivalent to the following code at run time.
In the original design, the C++ language designers categorized Type Traits in a simple way. And as the language evolves, Type Traits have been constantly modified. You can find all the latest definitions and descriptions of Type Traits from the link above. Apart from determining the traits of types, in <type_traits>, there also exist frequently used class templates such as is_same and enable_if. You can also find more information about the usage of these templates by following the link provided.
As for the implementation, the functionalities for the Type Traits usually rely on the template specifications type by type, which is a common method in template metaprogramming. For instance, the following code can be found in the <type_traits> header file in g++ 4.8.1.
template<typename _Tp, _Tp __v>
/// The type used as a compile-time boolean with true value.
/// The type used as a compile-time boolean with false value.
Thus, through specification, if we use const as the type parameter for template is_const, the constant value of the static member is true(1). This is because the compiler will choose the specification “Version 2” as it matches a const type better. Conversely, when the template matches better to specification “Version 1”, the value of constant static member would be false(0). See the example below:
__is_pod listed above is an instance of compiler intrinsics. In fact, the following Type Trait template classes all need compiler’s assistance:
So to summarize, template metaprogramming together with the assistance of compilers make the miracles of Type Traits happen. Furthermore, Type Trait makes programming with templates easier. Thus, C++11 adopts the feature into the new standard.
Authors: Garfee Guan, Yvonne Ma