Chapter 48. Boost.TypeTraits

    Since C++11, some functions provided by Boost.TypeTraits can be found in the standard library. You can access those functions through the header file . However, Boost.TypeTraits provides additional functions.

    Example 48.1. Determining type categories

    Example 48.1 calls several functions to determine type categories. boost::is_integral checks whether a type is integral – whether it can store integers. boost::is_floating_point checks whether a type stores floating point numbers. boost::is_arithmetic checks whether a type supports arithmetic operators. And boost::is_reference can be used to determine whether a type is a reference.

    boost::is_integral and boost::is_floating_point are mutually exclusive. A type either stores an integer or a floating point number. However, boost::is_arithmetic and boost::is_reference can apply to multiple categories. For example, both integer and floating point types support arithmetic operations.

    In , the result of the various functions is a value of type , which can be written directly to standard output. If the result is to be processed by a function template, it should be forwarded as a type, not as a bool value.

    Example 48.2. boost::true_type and boost::false_type

    Besides value, functions from Boost.TypeTraits also provide the result in type. While value is a bool value, type is a type. Just like value, which can only be set to true or false, type can only be set to one of two types: boost::true_type or boost::false_type. type lets you pass the result of a function as a type to another function.

    Example 48.2 uses another function from Boost.TypeTraits called boost::issame. This function expects two types as parameters and checks whether they are the same. To pass the results of boost::is_integral, boost::is_floating_point, boost::is_arithmetic, and boost::is_reference to boost::is_same, must be accessed. type is then compared with boost::true_type or boost::false_type. The results from boost::is_same are then read through _value again. Because this is a bool value, it can be written to standard output.

    introduces functions that check properties of types. boost::has_plus checks whether a type supports the operator operator+ and whether two objects of the same type can be concatenated. boost::has_pre_increment checks whether a type supports the pre-increment operator operator++. boost::has_trivial_copy checks whether a type has a trivial copy constructor. And boost::has_virtual_destructor checks whether a type has a virtual destructor.

    Example 48.3 displays true three times and false once.

    Example 48.4. Changing type properties with Boost.TypeTraits

    illustrates how type properties can be changed. boost::add_const adds const to a type. If the type is already constant, nothing changes. The code compiles without problems, and the type remains constant.

    Example 48.4 writes four times to standard output.