【发布时间】:2015-12-04 22:01:55
【问题描述】:
在使用函数模板时,我只能使用引用变量作为函数参数。
下面的程序(找到两个数字之间的最小值)工作正常。
//Program to calculate minimum among two numbers
#include<iostream>
using namespace std;
template <class ttype>
//Using reference variables
//as function parameters
ttype min(ttype& a, ttype& b)
{
ttype res = a;
if (b < a)
res = b;
return res;
}
int main()
{
int a = 5, b = 10;
int mini = min(a, b);
cout << "Minimum is: " << mini << endl;
return 0;
}
但是,当我改变如下功能时:
template <class ttype>
//Using normal variables
//as function parameters
ttype min(ttype a, ttype b)
{
ttype res = a;
if (b < a)
res = b;
return res;
}
我得到编译错误。
在使用函数模板时我们应该只使用引用变量吗?
【问题讨论】: