[英]Strange Template error : error C2783: could not deduce template argument
我創建了一個帶有2個diffrernt模板參數t1,t2和返回類型t3的簡單函數。 到目前為止沒有編譯錯誤。 但是當Itry從main調用函數時,我遇到錯誤C2783。 我需要知道以下代碼是否合法? 如果不是如何修復? 請幫忙!
template <typename t1, typename t2, typename t3>
t3 adder1 (t1 a , t2 b)
{
return int(a + b);
};
int main()
{
int sum = adder1(1,6.0); // error C2783 could not deduce template argument for t3
return 0;
}
編譯器無法從函數參數中推導出t3
。 您需要明確傳遞此參數。 更改參數的順序以使其成為可能
template <typename t3, typename t1, typename t2>
t3 adder1 (t1 a , t2 b)
{
return t3(a + b); // use t3 instead of fixed "int" here!
};
然后你可以用adder1<int>(1, 6.0)
來調用它。 如果你想將t3
推導到實際的加法結果,那就更難了。 C ++ 0x(下一個C ++版本的代號)將允許通過以下方式表示返回類型等於添加類型來執行此操作
template <typename t1, typename t2>
auto adder1 (t1 a , t2 b) -> decltype(a+b)
{
return a + b;
};
然后你可以在使用點明確地施放
int sum = (int) adder1(1,6.0); // cast from double to int
在當前的C ++版本中模擬這並不容易。 您可以使用我的促銷模板來執行此操作。 如果您覺得這對您來說相當混亂,並且您可以明確地提供返回類型,我認為最好繼續明確地提供它。 像Herb Sutter所說: “寫下你所知道的,知道你寫的是什么”
盡管如此,您可以使用該模板執行上述操作
template <typename t1, typename t2>
typename promote<t1, t2>::type adder1 (t1 a, t2 b)
{
return (a + b);
};
在嘗試推斷模板類型時,編譯器不會查看函數的實際代碼 。 如果你知道返回類型是int
,那么把它變成int
。
template <typename t1, typename t2>
int adder1 (t1 a , t2 b)
{
return int(a + b);
};
int main()
{
int sum = adder1(1,6.0); // error C2783 could not deduce template argument for t3
return 0;
}
在你的情況下,調用你的函數的唯一方法是adder1<int, double, int>(...)
。
你可以讓你的函數返回一個顯式的t3
參數或者通過引用傳遞這個參數,比如
adder(const t1& a, const t2&b, t3& result)
你總是返回一個int
因此不需要t3。 您可以將代碼修改為:
template <typename t1, typename t2>
int adder1 (t1 a , t2 b)
{
return int(a + b);
};
int main()
{
int sum = adder1(1,6.0); // error C2783 could not deduce template argument for t3
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.