如何在模板函数中传递文本
How literal are passed in template function
#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
#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&
。
非常量左值引用不能绑定到右值(例如文字),这就是为什么在第二种情况下会出现编译错误的原因。
相关文章:
- c++ 将成员函数的输出写入文本文件
- 您将如何连接"on the fly"文本+整数并将其传递给函数?
- 文本 RPG - 使用函数检查有效的输入
- 我可以使用谷歌 v8 在回调函数中获取 JavaScript 函数C++源文本吗?
- 文本 0 和 0 作为变量如何使用函数 __builtin_clz 产生不同的行为?
- 如何将函数的输出数据存储在文本文件中
- 如何使输入文本文件成为构造函数参数?c++
- 在C++中,从构造函数中将字符串文本分配给成员const char*变量时会发生什么
- 将字符串文本传递给需要字符串的函数
- 基于模板字符串文本返回的 c++ 函数指针
- 字符串文本左值和右值引用的函数重载
- 具有字符串文本构造函数的类不适用于 const 引用初始化
- 如何创建一个函数,该函数在文本中查找单词的匹配项,包括跳过
- 为什么插槽函数即使成功调用也无法插入文本
- 函数模板不适用于字符串文本
- 如何将“编辑文本值”传递给函数
- 是否有必要在模板化函数中强制转换文本常量?
- 文本类类型成员函数约束
- 函数读取最大和min int值,并用文本字符串返回
- 问题 - 递归函数以返回文本文件排列