函数形参问题

[复制链接]
 楼主| dfsa 发表于 2012-4-23 18:09 | 显示全部楼层 |阅读模式
函数模板形参 有点没弄明白
例子:
template<typename T>
void fun(T& t1, T& t2)
{....}

int main()
{
int n = 10;
fun(1,2);//① 正确
fun(n,2);//② 错误
return 0;
}

①和②这两个地方让我有点糊涂。①成功是因为T的类型此时被替换成了const int类型吗??
②错误的地方是因为n和数字2的类型不同(一个是int 一个是const int) 还是因为int&不能绑定const int

①是正确的 那么fun中 T&和const T&岂不是一样了????


函数模板形参这个地方 有什么规律可循吗
无冕之王 发表于 2012-4-23 18:32 | 显示全部楼层
与模板无关, 参数是int &也会错2行, const int&才行
秋天落叶 发表于 2012-4-23 20:09 | 显示全部楼层
error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
g++4.6.1 编译. 你那两个调用都是上面这个错误
xsgy123 发表于 2012-4-23 20:15 | 显示全部楼层
什么编译器?
火箭球迷 发表于 2012-4-23 20:18 | 显示全部楼层
感觉应该是VC6
您需要登录后才可以回帖 登录 | 注册

本版积分规则

282

主题

2404

帖子

2

粉丝
快速回复 在线客服 返回列表 返回顶部

282

主题

2404

帖子

2

粉丝
快速回复 在线客服 返回列表 返回顶部