2010-05-27 229 views
1

我創建了一個簡單的函數,其中包含2個diffrernt模板參數t1,t2和返回類型t3。 到目前爲止沒有編譯錯誤。但是當Itry從main調用該函數時,我遇到錯誤C2783。 我需要知道如果下面的代碼合法嗎?如果不是如何修復? 請幫忙!奇怪的模板錯誤:錯誤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; 
} 

回答

10

有沒有辦法讓編譯器推斷出函數的參數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++版本中對此進行模擬並不容易。您可以使用我的promote template來做到這一點。如果你覺得這個事情對你來說很困惑,並且你明確地提供了返回類型,我認爲最好是明確地提供它。像Herb Sutter says「寫你知道什麼,並知道你寫的什麼?」

Nontheless您可以使用該模板

template <typename t1, typename t2> 
typename promote<t1, t2>::type adder1 (t1 a, t2 b) 
    { 
     return (a + b); 
    }; 
+0

'std :: plus '任何人? :) +1 – 2010-05-27 11:32:03

+0

非常感謝您的答覆 – osum 2010-05-30 17:30:37

0

在你的情況下,調用你的函數的唯一方法是adder1<int, double, int>(...)

你可以讓你的函數由參考返回一個明確的說法t3或通過這樣的說法,像

adder(const t1& a, const t2&b, t3& result) 
0

你總是返回,因此不需要一個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; 

} 
3

當試圖推斷出模板類型,編譯器是不會看函數的實際代碼。如果您知道退貨類型爲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; 
}