2009-02-03 108 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