2010-07-24 54 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) { ... }