【问题标题】:GCC 4.0: "no matching function to call" in template functionGCC 4.0:模板函数中的“没有要调用的匹配函数”
【发布时间】:2009-02-03 15:06:05
【问题描述】:

我想知道为什么以下人为设计的示例代码在 Visual Studio 2005 中运行良好,但在 GCC 中生成错误(调用 Interpolate() 时“没有要调用的匹配函数”,如下所示)。

另外,我该如何解决这个问题?似乎错误消息只是一条通用消息,因为 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&)'

感谢您的帮助,

阿德里安

【问题讨论】:

    标签: c++ templates gcc


    【解决方案1】:

    我认为你在函数定义中根本不需要模板,因为它是与类内联定义的

    TMyPointTemplate Interpolate(const TMyPointTemplate &OtherPoint)const {
    

    应该这样做。

    当你使用模板来定义非内联函数时,我认为你需要像这样的 class 关键字。

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

    【讨论】:

    • 优秀的答案。非常感谢你的帮助! :-)
    【解决方案2】:

    Evan 的 answer 解决了这个问题,但我认为解释原因可能会很有用。

    正如所写,Interpolate 是一个成员模板函数,具有一个未命名的“非类型模板参数”(而不是几乎可以肯定是您想要的类型模板参数)。为了说明这一点,我们可以给这个参数一个名字:

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

    现在我们可以看到如何调用该函数了,我们只需要为 't' 提供一个值:

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

    在 'T' 之前添加 classtypename 将其声明为类型模板参数。但是,仅进行该更改将导致错误,因为标识符“T”已被用于封闭类模板中的模板参数名称。我们必须更改成员函数模板的模板参数名称:

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

    【讨论】:

    • 确实很有见地。非常感谢你的帮助! :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 2017-09-26
    • 2021-06-28
    • 2011-03-03
    • 1970-01-01
    相关资源
    最近更新 更多