Function Templates

Contents[Show]

A function template is a family of functions. In this post, I want to dive deeper into function templates.

 templatesNew

Here is a short reminder to get you on the same page.

When you instantiate a function template such as max for int and double

template <typename T>
T max(T lhs,T rhs) {
    return (lhs > rhs)? lhs : rhs;
}

int main() {
  
    max(10, 5);
    max(10.5, 5.5);
  
}

the compiler generates a fully specialized function template for int and double: max<int> and max<double>. The generic part is in both cases empty: template<> Thanks to C++ Insights, here are the insights.

functionTempateIntDouble

Okay, now I can dive into the details. What happens, when function templates and non-template functions (in short functions) overload?

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Stay informed about my mentoring programs.

 

 

Subscribe via E-Mail.

Overloading of Function Templates and Functions

Let me use the function max once more. This time I instantiate it for float and double, and I provide a function max taking also doubles.

Here is my next example:

template <typename T>
T max(T lhs,T rhs) {
    return (lhs > rhs)? lhs : rhs;
}

double max(double lhs, double rhs) {
    return (lhs > rhs)? lhs : rhs;
}

int main() {
  
    max(10.5f, 5.5f); // (1)
    max(10.5, 5.5);   // (2)
  
}

 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 float to double.
  • 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.

functionTemplateFloatDouble

The screenshot shows it explicitly. Only the use of the function template max with 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.

template <typename T>
T max(T lhs,T rhs) {
    return (lhs > rhs)? lhs : rhs;
}

int main() {
  
    max(10.5f, 5.5);
  
}

 Let's try it out on C++ Insights:

functionTemplatesFloatDoubleError

 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.
  • For 10.5f the compiler deduces float for T, for 5.5 the compiler deduces double for T.
  • Of course, T cannot be float and double at 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 just introduce a second type parameter.

template <typename T, typename T2>
??? max(T lhs,T2 rhs) {
    return (lhs > rhs)? lhs : rhs;
}

int main() {
  
    max(10.5f, 5.5);
  
}

This is easy! Right? But there is a serious 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 was a challenging task before C++11, but it is quite easy with C++11.

Here are a few solutions I have in mind:

 

// automaticReturnTypeDeduction.cpp

#include <type_traits>

template <typename T1, typename T2>      // (1)
typename std::conditional<(sizeof(T1) > sizeof(T2)), T1, T2>::type max1(T1 lhs,T2 rhs) {
    return (lhs > rhs)? lhs : rhs;
}

template <typename T1, typename T2>      // (2)
typename std::common_type<T1, T2>::type max2(T1 lhs,T2 rhs) {
    return (lhs > rhs)? lhs : rhs;
}

template <typename T1, typename T2>     // (3)
auto max3(T1 lhs,T2 rhs) {
    return (lhs > rhs)? lhs : rhs;
}

int main() {
  
    max1(10.5f, 5.5);                  
    max2(10.5f, 5.5);                  
    max3(10.5f, 5.5);                  
  
}

 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 auto.

  • max1 (line 1): typename std::conditional<(sizeof(T1) > sizeof(T2)), T1, T2>::type returns the type T1, or T2 that is bigger. std::conditional is a kind of compile-time ternary operator.
  • max2 (line2): typename td::common_type<T1, T2>::type returns the common type of the types T1 and T2. std::common_type can accept an arbitrary number of arguments.
  • max3 (line3): auto should be self-explanatory.
Maybe you are irritated by the typename in front of the return type of the function template max1 and 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.
 
Third disclaimer: I write in an additional post about dependent types.
 
Let's see what C++ Insights provides. I only show the template instantiations. If you want to analyze the entire program, follow this link: C++ Insights.
 
  • max1(line 1): You can only guess the return type. In the return statement, the smaller type (float) is converted to double. max1
  • max2(line 2): As for max1, the return statement gives an idea about the return type: the float value is converted to double.

max2

  • max3 (line 3): Now, we can see the return type explicitly. It is a double.

max3

 

What's next?

In this installment, I solved the challenge of different types of function arguments by using more than one type parameter. Next time, I 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, Animus24, 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, and Ann Shatoff.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build 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.

  • 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

Modernes C++,

RainerGrimmDunkelBlauSmall

 

Comments   

+1 #1 Kiran 2021-05-11 01:14
Hi Rainner,
Thanks for writing such awesome content.

Two description lines I found, might need improvement.

1. "Okay, now I can dive into the details. What happens, when I function templates and non-template functions (in short functions) overload?"
Into this line 'I' seems irrelevant

2. "The screenshot shows it explicitly. Only the use of the function template max for double (line 2) triggers the instantiations of the function template."
Into this sentence, I believe, in place of 'double' , expected is 'float'
Quote

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)

All tags

Blog archive

Source Code

Visitors

Today 105

Yesterday 7888

Week 7993

Month 152164

All 11633318

Currently are 174 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments