2010-08-04 109 views
2
template <typename T> void function(T arg1, 
    T min = std::numeric_limits<T>::min(), 
    T max = std::numeric_limits<T>::max()) 
{ 
} 

template <> void function<int>(int arg1, int min,int max) 
{ 
} 

int main(int argc,char* argv[]) 
{ 
    function<int>(1); 
} 

它在語法錯誤C2689和C2059上的函數默認參數行::令牌。 但沒有專業化,它做得很好。如果我更改默認參數 和還在做專業化:模板函數專門化默認參數

template <typename T> void function(T arg1, 
    T min = T(0), 
    T max = T(1)) 
{ 
} 
template <> void function<int>(int arg1, int min,int max) 
{ 
} 

沒了的問題。

現在如果我這樣使用它:function<int>(1,2,3);function<float>(1.0f)它很好,所以看起來如果模板函數是專用的,我們必須在調用它時重寫默認參數?

但在我的第二種情況下,我將其替換爲std::numeric_limits<T>::..T(..)在調用function<int>(1)時沒有語法錯誤,爲什麼?

(我'使用Visual Studio 2010 x64)的

因爲原來的問題是由於錯誤的,現在的問題變爲如何解決辦法呢?

回答

3

代碼沒有問題; Comeau Online,Intel C++ 11.1和g ++ 4.1.2成功編譯。

我想這是編譯器中的一個錯誤。我最近提交了一個與Visual C++ 2010編譯器相關但略有不同的bug report


作爲一種變通方法,你可以用呼叫:

template <typename T> 
T get_limits_min() { return std::numeric_limits<T>::min(); } 

template <typename T> 
T get_limits_max() { return std::numeric_limits<T>::max(); } 

template <typename T> void function(T arg1, 
    T min = get_limits_min<T>(), 
    T max = get_limits_max<T>()) 
{ 
} 

醜嗎?相當。


我張貼在響應以下,以the bug you reported on Microsoft Connect:

主要模板必須具有默認參數值的參數。默認參數值必須是不在全局名稱空間中的類模板的成員函數。

以下是最少的代碼重現:

namespace N 
{ 
    template <typename T> 
    struct S 
    { 
     static T g() { return T(); } 
    }; 
} 

template <typename T> void f(T = N::S<T>::g()) { } 

template <> void f<>(int) { } 

int main() 
{ 
    f<int>(); 
} 

編譯器發出以下錯誤,無論在其中主模板被定義的行:

error C2589: '::' : illegal token on right side of '::' 
error C2059: syntax error : '::' 

有趣的是,存在另一個問題如果類模板位於全局名稱空間中。給出下面的代碼:

template <typename T> 
struct S 
{ 
    static T g() { return T(); } 
}; 

template <typename T> void f(T = ::S<T>::g()) { } 

template <> void f<>(int) { } 

int main() 
{ 
    f<int>(); 
} 

編譯器發射線路上的下面的錯誤在其上定義的主模板:

error C2064: term does not evaluate to a function taking 0 arguments 

的這兩個例子測試用例合式C++程序。

+0

如何向Microsoft報告此錯誤? – uray 2010-08-04 03:31:21

+0

@uray:您可以通過我列出的錯誤報告鏈接在connect.microsoft.com上提交它;您必須登錄並打開新的缺陷。如果你不想,我會盡量減少這個問題,以及我之前報告給一個普通樣本的問題,並重新提交問題。讓我知道;我很樂意提供幫助。 – 2010-08-04 03:33:27

+0

我現在報告錯誤。 – uray 2010-08-04 03:35:44

1

這裏的答案是https://stackoverflow.com/a/13566433/364084https://stackoverflow.com/a/27443191/364084,這是由於在windows頭文件中定義了min和max宏。下面的代碼應該通過防止宏擴展來工作:

template <typename T> void function(T arg1, 
    T min = (std::numeric_limits<T>::min)(), 
    T max = (std::numeric_limits<T>::max)()) 
{ 
} 

template <> void function<int>(int arg1, int min,int max) 
{ 
} 

int main(int argc,char* argv[]) 
{ 
    function<int>(1); 
}