TypeTraits

C++ Core Guidelines: Programming at Compile Time with Type-Traits (The Second)

The type-traits library supports type checks, type comparisons, and type modifications at compile time. Right! Today, I write about type modifications at compile time.

TypeTraits

The Type-Traits Library

Type modification is the domain of template metaprogramming and, therefore, for the type-traits library.

Type Modifications

Maybe, you are curious about what is possible at compile time. A lot! Here are the most exciting metafunctions:

// const-volatile modifications:
remove_const;
remove_volatile;
remove_cv;
add_const;
add_volatile;
add_cv;
   
// reference modifications:
remove_reference;
add_lvalue_reference;
add_rvalue_reference;

// sign modifications:
make_signed;
make_unsigned;
 
// pointer modifications:
remove_pointer;
add_pointer;
 
// other transformations:
decay;
enable_if;
conditional;
common_type;
underlying_type;

 

To get an int from int or const int, you must ask for the type with ::type.

 

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    int main(){
        
        std::is_same<int, std::remove_const<int>::type>::value;        // true
        std::is_same<int, std::remove_const<const int>::type>::value;  // true
      
    }
    

     

    Since C++14, you can use _t to get the type, such as for std::remove_const_t:

     

    int main(){
        
        std::is_same<int, std::remove_const_t<int>>::value;        // true
        std::is_same<int, std::remove_const_t<const int>>::value;  // true
    }
    

     

    To get an idea of how valuable these metafunctions from the type-traits library are, here are a few use cases. Here is std::move in one line.

    • remove_reference: std::move and std::forward uses this function to remove the reference from its argument.
      • static_cast<std::remove_reference<decltype(arg)>::type&&>(arg);
    • decay: std::thread applies std::decay to its arguments. Their usage includes the function f a thread executes on its arguments args. Decay means that implicit conversions from array-to-pointer, and function-to-pointer is performed, and const/volatile qualifiers and references are removed.
    • enable_if: std::enable_if is a convenient way to use SFINAE. SFINAE stands for Substitution Failure Is Not An Error and applies during overload resolution of a function template. When substituting the template parameter fails, the specialization is discarded from the overload set but causes no compiler error. std::enable_if is heavily used in std::tuple.
    • conditional: std::conditional is the ternary operator at compile time.
    • common_type: std::common_type determines the common type of a group of types.
    • underlying_type: std::underlying_type determines the type of an enum.

    Maybe, you are not convinced about the benefit of the type traits library. Let me end my story with the type-traits with their primary goals: correctness and optimization.

    Correctness

    Correctness means, on one hand, that you can use the type-traits libraries to implement concepts such as Integral, SignedIntegral, and UnsignedIntegral.

    template <class T>
    concept bool Integral() {
        return is_integral<T>::value;
    }
    
    template <class T>
    concept bool SignedIntegral() {
        return Integral<T>() && is_signed<T>::value;
    }
    
    template <class T>
    concept bool UnsignedIntegral() {
        return Integral<T>() && !SignedIntegral<T>();
    }
    

     

    But it also means you can use them to make your algorithm safer. I used in my previous post, More and More Safe, the functions std::is_integral, std::conditional, std::common_type, and std::enable_if from the type-traits library to make the generic gcd algorithm successively safer.

    To get a better idea of the post More and More Safe , here is the starting point of my generic gcd algorithm.

    // gcd.cpp
    
    #include <iostream>
    
    template<typename T>
    T gcd(T a, T b){
      if( b == 0 ){ return a; }
      else{
        return gcd(b, a % b);
      }
    }
    
    int main(){
    
      std::cout << std::endl;
    
      std::cout << "gcd(100, 10)= " <<  gcd(100, 10)  << std::endl;
      std::cout << "gcd(100, 33)= " << gcd(100, 33) << std::endl;
      std::cout << "gcd(100, 0)= " << gcd(100, 0)  << std::endl;
    
      std::cout << gcd(3.5, 4.0)<< std::endl;         // (1)
      std::cout << gcd("100", "10") << std::endl;     // (2)
    
      std::cout << gcd(100, 10L) << std::endl;        // (3)
    
      std::cout << std::endl;
    
    }
    

     

    The output of the program shows two issues.

    gcd

    First, double (line 1) and the C-String (line 2) fail in the modulo operator. Second, using an integer and a long (line 3) should work. Both issues can be elegantly solved with the type-traits library.

    The type-traits are not only about correctness it’s also about optimization.

    Optimization

    The key idea of the type-traits library is relatively straightforward. The compiler analysis the used types and makes, based on this analysis decision about which code should run. In the case of the algorithm std::copy, std::fill, or std::equal of the standard template library, the algorithm is applied to each element of the range one-by-one or the entire memory. In the second case, C functions such as memcmp, memset, memcpy, or memmove are used, making the algorithm faster. The slight difference between memcpy and memmove is that memmove can deal with overlapping memory areas.

    The following three code snippets from the GCC 6 implementation clarify one point: The type-traits library checks help generate more optimized code.

     

    // fill  
    // Specialization: for char types we can use memset.                   
    template<typename _Tp>
      inline typename
      __gnu_cxx::__enable_if<__is_byte<_Tp>::__value, void>::__type         // (1)
      __fill_a(_Tp* __first, _Tp* __last, const _Tp& __c)
      {
        const _Tp __tmp = __c;
        if (const size_t __len = __last - __first)
        __builtin_memset(__first, static_cast<unsigned char>(__tmp), __len);
      }
    
    // copy
    
    template<bool _IsMove, typename _II, typename _OI>
      inline _OI
      __copy_move_a(_II __first, _II __last, _OI __result)
      {
        typedef typename iterator_traits<_II>::value_type _ValueTypeI;
        typedef typename iterator_traits<_OI>::value_type _ValueTypeO;
        typedef typename iterator_traits<_II>::iterator_category _Category;
        const bool __simple = (__is_trivial(_ValueTypeI)                   // (2)
                               && __is_pointer<_II>::__value
                               && __is_pointer<_OI>::__value
                               && __are_same<_ValueTypeI, _ValueTypeO>::__value);
    
        return std::__copy_move<_IsMove, __simple,
      }
    
    // lexicographical_compare
    
    template<typename _II1, typename _II2>
      inline bool
      __lexicographical_compare_aux(_II1 __first1, _II1 __last1,
    				  _II2 __first2, _II2 __last2)
      {
        typedef typename iterator_traits<_II1>::value_type _ValueType1;
        typedef typename iterator_traits<_II2>::value_type _ValueType2;
        const bool __simple =                                              // (3)
          (__is_byte<_ValueType1>::__value && __is_byte<_ValueType2>::__value
           && !__gnu_cxx::__numeric_traits<_ValueType1>::__is_signed
           && !__gnu_cxx::__numeric_traits<_ValueType2>::__is_signed
           && __is_pointer<_II1>::__value
           && __is_pointer<_II2>::__value);
    
      return std::__lexicographical_compare<__simple>::__lc(__first1, __last1,
                                                            __first2, __last2);
      }
    

     

    Lines 1, 2, and 3 show that the type-traits library is used to generate more optimized code. My post Type-Traits: Performance Matters, gives you more insight and has performance numbers with GCC and MSVC.

    What’s next?

    With constexpr, programming at compile time escapes its expert niche and becomes a mainstream technique. constexpr is programming at compile time with the typical C++-Syntax.

     

     

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, Philipp Lenk, Hobsbawm, and Charles-Jianye Chen.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Seminars

    I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

    Standard Seminars (English/German)

    Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

    • C++ – The Core Language
    • C++ – The Standard Library
    • C++ – Compact
    • C++11 and C++14
    • Concurrency with Modern C++
    • Design Pattern and Architectural Pattern with C++
    • Embedded Programming with Modern C++
    • Generic Programming (Templates) with C++
    • Clean Code with Modern C++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *