A function template is a family of functions. In this post, I want to dive deeper into function templates.
Here is a short reminder to get you on the same page.
When you instantiate a function template such as
the compiler generates a fully specialized function template for int and
max<double>. The generic part is, in both cases, empty:
template<> Thanks to C++ Insights, here are the insights.
Okay, now I can dive into the details. What happens when function templates and non-template functions (in short functions) overload?
Overloading of Function Templates and Functions
Let me use the function
max once more. This time I instantiate it for
double, and I provide a function
max also taking doubles.
Here is my following example:
You may guess my question. What happens in lines (1) and (2)? Here are a few questions?
- Line (1): Does the compiler choose the function template or the function and promote the
- Line (2): Either the function and the function templates are ideal fits. This seems to be ambiguous and may cause a compiler error.
The answer to questions is pretty intuitive and follows the general rule in C++. The compiler chooses the best-fitting function.
- Line (1): The function template is the better fit because the function would require a promotion from float to double.
- Line (2): The function template and the function are ideal fits. In this case, an additional rule kicks in. When both are equally good fits, the compiler prefers the function.
As before, C++ Insights helps to visualize this process.
The screenshot shows it explicitly. Only the use of the function template
float (line 2) triggers the instantiations of the function template.
Let’s go further in our journey through the basics of function templates.
First disclaimer: I ignore concepts in this post.
Different Template Arguments
Let me use my function template
max with two values having different types.
Let’s try it out on C++ Insights:
Wow! What is happening here? Why is the
float not promoted to a
double? Honestly, the compiler thinks differently, and let me explain how.
- The compiler deduces the template argument from the function argument if possible. In this case, it’s possible.
- The compiler does this process of template argument deduction for each function argument.
10.5fthe compiler deduces
5.5the compiler deduces
- Of course, T cannot be
doubleat the same time. Because of this ambiguity, the compilation failed.
Second disclaimer: I simplified the process of template argument deduction. I will write an additional post about template argument deduction for function templates and class templates in a future post.
Of course, we want to compare values of different types.
Two Type Parameters
The solution seems to be straightforward. I introduce a second type parameter.
This is easy! Right? But there is a severe problem. Do you see the three question marks as return type? This problem typically occurs when your function template has more than one type parameter. What should be the return type?
In this concrete case, should the return type be T, T2, or a Type R derived from T and T2? This task was challenging before C++11, but it is pretty easy with C++11.
Here are a few solutions I have in mind:
The first two versions
max1 (line 1) and
max2 (line 2) are based on the type-traits library. The third version
max3 (line 3) uses the automatic type deduction of
td::conditional<(sizeof(T1) > sizeof(T2)), T1, T2>::typereturns the type
T2that is bigger. std::conditional is a kind of compile-time ternary operator.
typename td::common_type<T1, T2>::typereturns the common type of the types T1 and T2. std::common_type can accept an arbitrary number of arguments.
autoshould be self-explanatory.
typenamein-front of the return type of the function template
max1and max2. T1 and T2 are dependent names. What is a dependent name? A dependent name is essentially a name that depends on a template parameter. In this case, we have to give the compiler a hint that T1 and T2 are types. Essentially, they can also be non-types or templates.
max1(line 1): You can only guess the return type. In the return statement, the smaller type (float) is converted to
max2(line 2): As for
max1, the return statement gives an idea about the return type: the float value is converted to
max3(line 3): Now, we can see the return type explicitly. It is a
In this installment, I solved the challenge of different types of function arguments by using more than one type parameter. Next time, I will take a different approach and explicitly specify the template arguments.
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, and Bhavith C Achar.
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|
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,