首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何定义命名空间中模板上声明的朋友运算符?

如何定义命名空间中模板上声明的朋友运算符?
EN

Stack Overflow用户
提问于 2017-05-01 13:37:07
回答 1查看 274关注 0票数 2

我有这样一门课:

代码语言:javascript
复制
namespace N
{
  template<unsigned Mantissa, unsigned Fraction>
  class C
  {
  //...
  public:
    friend C<Mantissa, Fraction> operator +(const C<Mantissa, Fraction> & left, const C<Mantissa, Fraction> & right);
  //...
  };
}

我一直在尝试分别定义这个operator +,但是我无法让它工作。

我试过:

代码语言:javascript
复制
    template<unsigned Mantissa, unsigned Fraction>
    N::C<Mantissa, Fraction> N::operator+(const N::C<Mantissa, Fraction> & left, const N::C<Mantissa, Fraction> & right)
    {
        //...
    }

但我得到了"C2244‘运算符+':无法将函数定义与现有声明相匹配“

我试过:

代码语言:javascript
复制
    template<unsigned Mantissa, unsigned Fraction>
    N::C<Mantissa, Fraction> operator+(const N::C<Mantissa, Fraction> & left, const N::C<Mantissa, Fraction> & right)
    {
        //...
    }

但我有链接错误。

我试过:

代码语言:javascript
复制
namespace N
{
    template<unsigned Mantissa, unsigned Fraction>
    C<Mantissa, Fraction> operator+(const C<Mantissa, Fraction> & left, const C<Mantissa, Fraction> & right)
    {
        //...
    }
}

但我也有同样的链接错误。

我不知道问题是什么,也不知道如何解决。operator必须是一个friend,因为它正在访问一个private字段(否则,我将不得不将字段设置为public,如果可以避免的话,我不想这样做)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-01 13:44:53

operator+在类定义中被声明为非模板函数,但是您试图在以后将它定义为函数模板,它们不匹配。如果要使其成为函数模板,则可以

代码语言:javascript
复制
namespace N
{
  // forward declaration of the class template
  template<unsigned Mantissa, unsigned Fraction>
  class C;
  // forward declaration of the function template
  template<unsigned Mantissa, unsigned Fraction>
  C<Mantissa, Fraction> operator +(const C<Mantissa, Fraction> & left, const C<Mantissa, Fraction> & right);

  template<unsigned Mantissa, unsigned Fraction>
  class C
  {
  //...
  public:
    // the instantiation of operator+ with template parameter of current Mantissa and Fraction becomes friend
    friend C<Mantissa, Fraction> operator + <>(const C<Mantissa, Fraction> & left, const C<Mantissa, Fraction> & right);
    //                                      ~~
  //...
  };
}

// definition of the function template
template<unsigned Mantissa, unsigned Fraction>
N::C<Mantissa, Fraction> N::operator+(const N::C<Mantissa, Fraction> & left, const N::C<Mantissa, Fraction> & right)
{
    //...
}

如果您想使它成为非模板函数,那么只需在类定义中定义它:

代码语言:javascript
复制
namespace N
{
  template<unsigned Mantissa, unsigned Fraction>
  class C
  {
  //...
  public:
    // defined as non-template
    friend C<Mantissa, Fraction> operator +(const C<Mantissa, Fraction> & left, const C<Mantissa, Fraction> & right) {
      //...
    }
  //...
  };
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43720007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档