How literal are passed in template function

65 Views Asked by At
#include <iostream>
using namespace std;

template <typename T>
void fun(const T& x)
{
  static int i = 10;
  cout << ++i;
  return;
}

int main()
{    
  fun<int>(1);  // prints 11
  cout << endl;
  fun<int>(2);  // prints 12
  cout << endl;
  fun<double>(1.1); // prints 11
  cout << endl;
  getchar();
  return 0;
}

output : 11 
         12
         11

How the constant literal are directly passed as a reference in function like fun < int >(1) and doesn't give compilation error? unlike in normal data type function call

#include<iostream>
using namespace std;

void foo (int& a){

cout<<"inside foo\n";

}
int main()
{
  foo(1);
  return 0;
}

It gives me compilation error:

prog.cpp: In function 'int main()':
prog.cpp:12:8: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
   foo(1);
        ^
prog.cpp:4:6: note: in passing argument 1 of 'void foo(int&)'
 void foo (int& a){
      ^

Please anybody explain how the constant literal are passed in template function . I think may be temporary object formed than function call takes place but not sure

1

There are 1 best solutions below

2
On BEST ANSWER

This is nothing to do with templates. The issue is that one function takes a const int& and the other takes an int&.

Non-const lvalue references cannot bind to rvalues (e.g. literals), which is why you get a compilation error in the second case.