如何在模板函数中传递文本

How literal are passed in template function

本文关键字:文本 函数      更新时间:2023-10-16
#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

常量文字如何在 fun(1) 等函数中作为引用直接传递并且不给出编译错误? 与普通数据类型函数调用不同

#include<iostream>
using namespace std;
void foo (int& a){
cout<<"inside foon";
}
int main()
{
  foo(1);
  return 0;
}

它给了我编译错误:

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){
      ^

请任何人解释如何在模板函数中传递常量文字。我认为可能是临时对象形成,而不是函数调用发生但不确定

这与模板无关。问题是一个函数采用const int&,另一个函数采用int&

非常量左值引用不能绑定到右值(例如文字),这就是为什么在第二种情况下会出现编译错误的原因。