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

How to define a friend operator declared on a template in a namespace?

我有一个 class 这样的:

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 +,但我无法让它工作。

我试过:

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

但是我得到了"C2244 'operator +': unable to match function definition to an existing declaration"

我试过:

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

但是我收到链接器错误。

我试过:

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,如果我可以避免它)。

operator+ 在 class 定义中被声明为非模板函数,但您稍后试图将其定义为函数模板,它们不匹配。如果你想把它做成函数模板,可以

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)
{
    //...
}

如果你想让它成为一个非模板函数,那么就在class定义里面定义它:

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) {
      //...
    }
  //...
  };
}