2009-02-03 104 views
5

我很奇怪,爲什麼下面的人爲的例子代碼在Visual Studio 2005中完全正常,但會產生在GCC錯誤(「沒有匹配的函數來調用」呼叫插值時() 如下所示)。GCC 4.0:「沒有匹配的函數來調用」模板功能

另外,我該如何解決這個問題?看來,錯誤消息只是一個通用消息,因爲GCC沒有針對問題的實際原因提供更具體的消息,並且它必須輸出一些內容。對於如何在沒有一些非常醜陋的解決方法的情況下繼續移植這個類,我有點不知所措。

namespace Geo 
{ 
    template <class T> 
    class TMyPointTemplate 
    { 
     T X,Y; 
    public: 
     inline TMyPointTemplate(): X(0), Y(0) {} 
     inline TMyPointTemplate(T _X,T _Y): X(_X), Y(_Y) {} 
     inline T GetX()const { return X; } 
     inline T GetY()const { return Y; } 
     //... 
     template<T> TMyPointTemplate<T> Interpolate(const TMyPointTemplate<T> &OtherPoint)const 
     { 
      return TMyPointTemplate((X+OtherPoint.GetX())/2,(Y+OtherPoint.GetY())/2); 
     }   
    }; 
    typedef TMyPointTemplate<int> IntegerPoint; 
} 

Geo::IntegerPoint Point1(0,0); 
Geo::IntegerPoint Point2(10,10); 
Geo::IntegerPoint Point3=Point1.Interpolate(Point2); //GCC PRODUCES ERROR: no matching function for call to 'Geo::TMyPointTemplate<int>::Interpolate(Geo::IntegerPoint&)' 

感謝您的幫助,

阿德里安

回答

9

我不認爲你需要的模板存在於所有的功能定義,因爲它與類

TMyPointTemplate Interpolate(const TMyPointTemplate &OtherPoint)const { 
聯定義

應該做的。

而當你使用模板來定義功能不在線,我認爲你需要在那裏class關鍵字這樣。

template<class T> // <- here 
TMyPointTemplate<T> TMyPointTemplate<T>::Interpolate(const TMyPointTemplate<T> &OtherPoint)const { 
+0

優秀的答案。非常感謝你的幫助! :-) – 2009-02-03 16:20:05

9

Evan's answer解決了這個問題,但我認爲這可能有助於解釋原因。

書面,插值是一個未命名的「非類型模板參數」(而不是類型模板參數這幾乎肯定是您的本意)的成員模板函數。爲了證明這一點,我們可以給該參數的名稱:

template<T t> TMyPointTemplate<T> Interpolate 
     (const TMyPointTemplate<T> &OtherPoint)const 

而且我們現在可以看到如何調用該函數,我們只需要提供「T」的值:

Geo::IntegerPoint Point3=Point1.Interpolate <0> (Point2); 

添加類別typename此處'T'之前,會將其聲明爲類型模板參數。但是,僅僅進行該更改將導致錯誤,因爲標識符'T'已被用於封閉類模板中的模板參數名稱。我們必須更改成員函數模板的模板參數的名稱:

template <class T> 
class TMyPointTemplate 
{ 
public: 
    //... 
    template<class S> TMyPointTemplate<T> Interpolate 
       (const TMyPointTemplate<S> &OtherPoint) const 
    { 
    return ...; 
    }      
}; 
+0

確實非常有見地。非常感謝你的幫助! :-) – 2009-02-03 16:21:01