The Type-Traits Library: Correctness
The two main goals of the type-traits library are compelling: correctness and optimization. Today, I write about correctness.
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;
Modernes C++ Mentoring
Be part of my mentoring programs:
Do you want to stay informed about my mentoring programs: Subscribe via E-Mail.
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 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
appliesstd::decay
to its arguments. The arguments ofstd::thread
, including the executed functionf
and their argumentsargs
. Decay means that implicit conversions from array-to-pointer, function-to-pointer is performed, andconst/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.
The compiler complains immediately that a double
or a const cha
r* 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.cp
p are equivalent.
Now, the error message is more verbose such as the previous one.
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:
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, 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, Matthieu Bolt, 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, and Philipp Lenk.
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.
Bookable
German
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
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++
New
- Clean Code with Modern C++
- C++20
Contact Me
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,
Leave a Reply
Want to join the discussion?Feel free to contribute!