The Type-Traits Library: Correctness

Contents[Show]

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

 templatesTypeTraits

The type-traits library enables it to type queries, type comparisons, and type modifications at compile time. In my previous post about the type traits library, I only wrote about type queries, and type comparison. 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.

 

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 just 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 useful 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. It means that 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.

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Stay informed about my mentoring programs. Subscribe for the news.

 

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 directly the type-traits functions 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 such 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 it's 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

Honestly, I don't think that 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'm going to 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, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Evangelos Denaxas, 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, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, and Wolfgang Fütterer.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, Ralf Abramowitsch, John Nebel, Mipko, Alicja Kaminska, and Matthias Grün.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

Seminars

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

Bookable (Online)

German

Standard Seminars (English/German)

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

New

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

Mentoring

Stay Informed about my Mentoring

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 2011

Yesterday 5448

Week 28924

Month 158429

All 10703545

Currently are 150 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments