templatesTypeTraits

The Type-Traits Library: Correctness

The two main goals of the type-traits library are compelling: correctness and optimization. Today, I write about correctness.

 templatesTypeTraits

The type-traits library enables it to type queries, comparisons, and modifications at compile time. In my previous post about the type traits library, I only wrote about type queries and comparisons. Before I write about the correctness aspect of the type-traits library, I want to write a few words about type modifications.

Type Modifications

The type-traits library offers many metafunctions to manipulate types. Here are the most interesting ones.

 

// 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 an int or a const int, you have to ask for the type with ::type.

 

Rainer D 6 P2 500x500

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (open)
  • "Generic Programming (Templates) with C++": October 2024
  • "Embedded Programming with Modern C++": October 2024
  • "Clean Code: Best Practices for Modern C++": March 2025
  • Do you want to stay informed: Subscribe.

     

    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 with std::remove_const_t:

    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 helpful these metafunctions from the type-traits library are, here are a few examples.

    • std::decay: std::thread applies std::decay to its arguments. The arguments of std::thread , including the executed function f and their arguments args. Decay means that implicit conversions from array-to-pointer, function-to-pointer is performed, and const/volatile qualifiers and references are removed.
    • 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. If substituting the template parameter fails, the specialization is discarded from the overload set, but this failure causes no compiler error.
    • std::conditional is the ternary operator at compile time?
    • std::common_type determines the common type among all types to which all types can be converted.
    • 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 series of posts to the type-traits library with its two main goals: correctness and optimization.

    Correctness

    Correctness means that you can use the type-traits library in C++11 to make your algorithm safer. The following implementation of the gcd algorithm requires that the binary modulo operator is valid for its arguments.

    // gcd2.cpp
    
    #include <iostream>
    #include <type_traits>
    
    template<typename T>
    T gcd(T a, T b) {
        static_assert(std::is_integral<T>::value, "T should be an integral type!");  // (1)
        if( b == 0 ){ return a; }
        else{
            return gcd(b, a % b);
        }
    }
    
    int main() {
    
        std::cout << gcd(100, 33) << '\n';
        std::cout << gcd(3.5,4.0) << '\n';
        std::cout << gcd("100","10") << '\n';
    
    }
    

     

    The error message is quite explicit.

    gcd2

    The compiler complains immediately that a double or a const char* is not an integral data type. Consequentially, the static_assert expression in (1) fired

    But correctness means that you can use the type-traits libraries to implement concepts such as Integral, SignedIntegral, and UnsignedIntegral in C++20.

    template <typename T>
    concept Integral = std::is_integral<T>::value;                      // (1)
    
    template <typename T>
    concept SignedIntegral = Integral<T> && std::is_signed<T>::value;   // (2)
    
    template <typename T>
    concept UnsignedIntegral = Integral<T> && !SignedIntegral<T>;
    

     

    The concept Integral uses the type-traits functions directly std::is_integral (1) and the concept SignedIntegral the type-traits function std::is_signed (2).

    Let’s try it out and use the concept Integral directly.

     

    // gcdIntegral.cpp
    
    #include <iostream>
    #include <type_traits>
    
    template <typename T>
    concept Integral = std::is_integral<T>::value;
    
    template <typename T>
    concept SignedIntegral = Integral<T> && std::is_signed<T>::value;
    
    template <typename T>
    concept UnsignedIntegral = Integral<T> && !SignedIntegral<T>;
    
    Integral auto gcd(Integral auto a, decltype(a) b) {
        if( b == 0 ){ return a; }
        else{
            return gcd(b, a % b);
        }
    }
    
    int main() {
    
        std::cout << gcd(100, 33) << '\n';
        std::cout << gcd(3.5,4.0) << '\n';
        std::cout << gcd("100","10") << '\n';
    
    }
    

     

    Now, the gcd algorithm is easier to read. It requires that the first argument a and its return type are integral data types. To ensure that the second argument b has the same type as the first type a I specified its type as decltype(a). Consequentially, this implementation of the gcd algorithm and the previous one in gcd2.cpp are equivalent.

    Now, the error message is more verbose such as the previous one.

    gcdIntegral

    The error message of the GCC is not only too verbose but also too difficult to read. Let me try out Clang on the Compiler Explorer. The error message about the erroneous usage of double reads like prose:

    gcdIntegralClang

    I don’t think an error message could be easier to read.

    Finally, I wanted to try out the latest Microsoft Visual Studio Compiler. This compiler supports concepts with one exception: the so-called abbreviated function template syntax. You may already guess it. I used the abbreviated function template syntax in my gcd algorithm. You can read more about this nice syntax in my previous post: C++20: Concepts – Syntactic Sugar.

    What’s next?

    Of course, you know what I will write about in my next post: the performance story of the type-traits library.

     

    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, 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, 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, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.

    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

    Modernes C++ GmbH

    Modernes C++ Mentoring (English)

    Do you want to stay informed about my mentoring programs? Subscribe Here

    Rainer Grimm
    Yalovastraße 20
    72108 Rottenburg

    Mobil: +49 176 5506 5086
    Mail: schulung@ModernesCpp.de
    Mentoring: www.ModernesCpp.org

    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 *