+ 2

Please, Explain the following code...

#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; } //Output is 223 //I was expecting 234

27th May 2019, 6:54 PM
Sp Maurya
Sp Maurya - avatar
3 Answers
+ 5
f is templated, so f(int) is not the same as f(double) or f(float). Therefore f(int) and f(float/double) will have their own distinct static int i; What you're used to is writing a function f(int) not templated and the compiler doing the implicit conversion for you when you call it f(1.0).
27th May 2019, 7:08 PM
Paul
+ 2
You're welcome :)
27th May 2019, 7:39 PM
Paul
+ 1
Paul oh that was the concept, ok thanks for your help i got it...
27th May 2019, 7:11 PM
Sp Maurya
Sp Maurya - avatar