c++ - How literal are passed in template function -


#include <iostream> using namespace std;  template <typename t> void fun(const t& x) {   static int = 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 constant literal directly passed reference in function fun < int >(1) , 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&' rvalue of type 'int'    foo(1);         ^ prog.cpp:4:6: note: in passing argument 1 of 'void foo(int&)'  void foo (int& a){       ^ 

please explain how constant literal passed in template function . think may temporary object formed function call takes place not sure

this nothing templates. issue 1 function takes const int& , other takes int&.

non-const lvalue references cannot bind rvalues (e.g. literals), why compilation error in second case.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -