2015-12-04 36 views
0

使用函數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; 
} 

我得到的編譯錯誤。

我們是否應該在使用函數模板時只使用引用變量?

回答

2

min衝突與std::min因爲你是using namespace std;

您可以執行以下步驟來解決這個問題,其中明確表示使用min即以外的所有命名空間:

int mini = ::min(a, b); 

或者,擺脫它的工作原理是using

這兩個解決方案都適用於gcc,&,沒有它。

1

那是因爲min與std :: min衝突。爲你的函數使用不同的名字,或者不要使用「using namespace std」,或者把你的函數放在不同的命名空間中,或者使用這個:

int mini = ::min(a, b);