Question about Template Function Calls C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Question about Template Function Calls C++

Hello, I came across this code by a user called 'Paracoder' in a Sololearn challenge, where there is a template function, and in main it is called for arguments 1, 1.0, and 1. #include <iostream> using namespace std; template <class T> void f(T) { static int i=1; cout << ++i; } int main() { f(1); f(1.0); f(1); return 0; } The output of this code makes it seem like there are actually two different functions with two different i variables. Is this actually what is happening?

18th Jul 2021, 5:36 PM
Edward Finkelstein
Edward Finkelstein - avatar
2 Answers
+ 6
For different template parameters, a different function (or class/type-alias/variable) is created. So, in your code, 2 functions will be created - f<int>() and f<double>(). As f<int>() is not the same function as f<double>(), the static variables are also different. This is actually a very good example to demonstrate how templates work.
18th Jul 2021, 5:57 PM
XXX
XXX - avatar
+ 2
That’s what I figured, thanks XXX
18th Jul 2021, 9:30 PM
Edward Finkelstein
Edward Finkelstein - avatar