In my last post, Template Arguments, I wrote about function template type deduction (C++98) and auto type deduction (C++11). Today I wear more modern hats. I start with automatic type deduction of non-type template parameters and class templates (C++17) and finish with automatic type deduction of concepts (C++20).
Following the chronological order, let me start with two C++17 features: type deduction of non-type template parameters and type deduction of class templates in C++17.
Automatic type deduction of non-type template parameters
First of all. What are non-type template parameters? These are
nullptr, integral values such as
int, lvalue references, pointer, enumerations, and with C++20 floating-point values. Most of the time, integral types are used, and so do I.
After this theory, let’s start with an example.
By using auto in (1) in the template signature, N is a non-type template parameter. The compiler will automatically deduce it. You can also partially specialize for int (2). The template instantiation (3) will use the primary template (1), and the following template instantiation the partial specialization for int (4).
The usual type modifiers can be used to constrain the type of the non-type template parameters.
In this declaration of a class template
S, p must be a pointer to const.
The automatic type deduction for non-type templates can also be applied to variadic templates.
VariadicTemplate can deduce an arbitrary number of non-type template parameters. TypeVariadicTemplate will only deduce the first template parameter. The remaining templated parameters will be of the same type as the first type:
Automatic type deduction from class templates makes the usage of class templates quite comfortable.
Automatic Type Deduction of Class Templates
A function template can deduce its type parameters from its function arguments. But that was not possible for particular functions: constructors of class templates. With C++17, this statement is simply wrong. A constructor can deduce its type parameters from its constructor arguments. Here is the first example.
Let me say a few words about the
main function. The instantiation of the function template
has been valid since the first C++ standard C++98, but the instantiation of the class template
ShowMe since C++17. From the user’s perspective, using functions templates or class templates feels just like an ordinary function or class.
Maybe, you are not convinced. Here are more examples of class template argument deduction.
The comments show the C++17 compiler deduced types. Thanks to C++ Insights, you can visualize this process of template argument deduction.
The last two examples to std::pair and std::tuple are pretty interesting. Before C++17, we used factory functions such as std::make_pair or std::make_tuple to create a std::pair or a std::tuple without specifying the type parameters. In contrast to class templates, the compiler could deduce the type parameter from the function arguments. Here is a simplified version of
The compiler deduces the same type for
pair2. With C++17, we don’t need this factory function anymore and can directly invoke the constructor of
std::pair to get
You can study the program on C++ Insights.
You may wonder why my function template
make_pair2 took its arguments by value.
std::make_pair decays its arguments, and so does my function template
make_pair2. I wrote about the decay of function arguments in my last post Template Arguments.
Before I write a few words about the automatic type deduction with concepts, I want to emphasize is explicit. Automatic type deduction is more than convenient. It’s a security feature. You cannot make an error when you don’t specify the type.
All errors are only because I explicitly specified the type:
int a1triggers the narrowing conversion from
func<float>(5.5)causes the conversion from the
Class<std::string> class1("class")creates a C++-string initialized with a C-string.
If you want to study the program, here it is: C++ Insights.
There is not much to add to the story of automatic type deduction when concepts come into play.
Automatic Type Deduction with Concepts
Automatic type deduction with concepts work like expected:
Whether you use an unconstrained placeholder (
auto in line 1), a constrained placeholder (a concept in line 2), or a restricted template parameter (a concept in line 3), the compiler deduces the expected type. C++ Insights helps to visualize the type deduction.
In my next post, I will write about the next exciting feature of templates: specialization. You can fully specialize a function template or class template. Additionally, a class template can be partially specialized.
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|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- 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++
- Clean Code with Modern C++
- 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,