Check Types

Template Metaprogramming is programming at compile time. But what has template metaprogramming in common with the type-traits library? A lot! The type-traits library is pure template metaprogramming, tamed in a library. With this post my presentation of the type-traits library becomes more structured.

Check type properties

The type-trait library supports primary and composite type categories. You get the answer with the attribute value.

Primary type categories

C++ has 14 primary type categories. They are complete and orthogonal. These means that each type is exactly member of one type category. The check for the type categories is independent of the type qualifiers const or volatile.

Thanks to the using of the flag std::boolalpha in line 22 the program displays true or false instead of 1 or 0. Each call of the 14 primary type categories returns true.

How does the magic work?

The key of the technique is based on templates and template specialization, a few conventions, and lot of typing. I wrote a possible implementation of the function template std::integral. std::integral will check, if the type is integral.

I use in my implementation the namespace rgr and compare my implementation with type-traits implementation in the namespace std. The invocation of the function template rgr::is_integral<int>::value (line 69) causes under the hood the invocation of the expression rgr::true_type::value (line 77), because integral<int> is derived from true_type (line 42). rgr::true_type::value is an alias for rgr::integral_constant<bool, true>::value (line 17). I use only in the example the static constexprvalue of the class integral_constant. integral_constant is the base class of the type-traits functions.

For completeness the output of the program. My implementation behaves like the type-traits library.

Based on the 14 primary type categories there are 7 composite type categories in C++.

Composite type categories

The is_fundamental type categorie uses the function template is_same. More about i in the next post in which I will write about type comparisons with the type-traits library.

There are more type checks possible with the type-traits.

Type properties

In addition to the primary and composite type categories you can check the type properties.

Many of the function templates like is_trivially_copyable have the name component trivially. That means that these methods have to be generated by the compiler and not by the developer. A method that you explicitly request from the compiler with the keyword default is also trivial.

What's next?

The type-traits library has a lot to offer. I will write in the next post about type comparison and type modifications at compile time.

Go to Leanpub/cpplibrary"What every professional C++ programmer should know about the C++ standard library".Get your e-book. Support my blog.