2010-07-24 56 views
5

的錯誤是在this代碼:聊齋志異「無法推導出模板參數的‘T’」的錯誤

//myutil.h 
template <class T, class predicate> 
T ConditionalInput(LPSTR inputMessage, LPSTR errorMessage, predicate condition);  

//myutil.cpp 
template <class T, class Pred> 
T ConditionalInput(LPSTR inputMessage, LPSTR errorMessage, Pred condition) 
{ 
     T input 
     cout<< inputMessage; 
     cin>> input; 
     while(!condition(input)) 
     { 
       cout<< errorMessage; 
       cin>> input; 
     } 
     return input; 
} 

... 

//c_main.cpp 
int row; 

row = ConditionalInput("Input the row of the number to lookup, row > 0: ", 
"[INPUT ERROR]: Specified number is not contained in the range [row > 0]. " 
"Please type again: ", [](int x){ return x > 0; }); 

的錯誤是:

Error 1  error C2783: 'T ConditionalInput(LPSTR,LPSTR,predicate)' : 
could not deduce template argument for 'T' c_main.cpp  17  1 

我一直在掙扎了好幾個小時但似乎無法找到解決方案。我相信錯誤可能是微不足道的,但在類似情況下,我找不到其他人遇到錯誤。 非常感謝!

編輯:由弗雷德裏克Slijkerman作出修正解決一個問題而造成另一種。這一次的錯誤是:

Error 1 error LNK2019: unresolved external symbol "int __cdecl ConditionalInput<int,class `anonymous namespace'::<lambda0> >(char *,char *,class `anonymous namespace'::<lambda0>)" ([email protected]<lambda0>@[email protected]@@@YAHPAD0V<lambda0>@[email protected]@@Z) referenced in function _main 

請耐心和我一起幫我解決這個問題。

回答

6

C++不能推導函數的返回類型。它只適用於它的論點。 你必須明確地呼叫ConditionalInput<int>(...)

+0

已編輯,因爲<>需要替換爲lt/gt。 – Scharron 2010-07-24 10:14:46

+0

上述答案的評論中的正確答案。雖然這個用戶持有它的信用。 – Johnny 2010-07-24 10:20:38

3

使用

row = ConditionalInput<int>(...) 

明確指定返回類型。

+0

我沒有指定第二模板類型? – Johnny 2010-07-24 10:08:56

+1

沒有必要,扣除適用於參數。 – Scharron 2010-07-24 10:10:29

+0

之後我又犯了一個錯誤,這個錯誤讓我更加頭疼。它是這樣的:錯誤錯誤LNK2019:無法解析的外部符號「int __cdecl ConditionalInput >(char *,char *,class'anonymous namespace':: )」 $ ConditionalInput @ HV @?A0x109237b6 @@@@ YAHPAD0V @?A0x109237b6 @@@ Z)在函數中引用_main \t C:\ Users \ CodeMaster \ documents \ visual studio 2010 \ Projects \ Challenge8 - Pascals Triangle \ Challenge8 - Pascals三角\ c_main.obj \t Challenge8 - 楊輝三角形 – Johnny 2010-07-24 10:11:05

0

我注意到你還需要先指定返回類型,如果它被明確稱爲Conditional<int>(...)

template <class T, class A> 
T function (A) { ... } 

,而下面將產生編譯錯誤:

template <class A, class T> 
T function (A) { ... }