使用函數tempelate時,我只能使用參考變量作爲函數參數。C++ |只有參考變量在函數模板中有效
下面的程序(找到兩個數字之間的最小值)工作正常。
//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;
}
我得到的編譯錯誤。
我們是否應該在使用函數模板時只使用引用變量?