在 C++ 中为模板 class 重载运算符 ostream 不起作用

overloading operator ostream for template class in c++ not working

所以我有这个模板 class:

template<class T = int, unsigned int SIZE =2>
class FixedPoint {
   public:
            explicit FixedPoint(T dollars = 0);
            FixedPoint(T dollars, T cents);

            friend std::ostream& operator<<(std::ostream& os ,const FixedPoint& price);

    private:
        static long digitsAfterDotFactor();
        long sizeAfterDot;
        T dollars;
        T cents;
};

这是h文件class下的定义

template<class T,unsigned int SIZE>
inline std::ostream& operator<<(std::ostream& os ,const FixedPoint<T,SIZE>& price){
    os << price.dollars << "." << price.cents;
    return os;
}

代码给出了以下错误:

friend declaration ‘std::ostream& operator<<(std::ostream&, const FixedPoint<T, SIZE>&)’ declares a non-template function

我尝试在声明中添加模板名称,但它无法识别 T class,我该怎么办?我应该为每种类型制作规范模板吗?

如错误信息所述,friend 声明声明了一个 non-template operator<<,但它被定义为模板,它们不匹配。

您可以在 friend 声明中引用运算符模板,例如

// forward declaration
template<class T = int, unsigned int SIZE =2>
class FixedPoint;

// declaration
template<class T,unsigned int SIZE>
std::ostream& operator<<(std::ostream& os ,const FixedPoint<T,SIZE>& price);

template<class T, unsigned int SIZE>
class FixedPoint {
   public:
            ...
            friend std::ostream& operator<< <T, SIZE> (std::ostream& os ,const FixedPoint<T, SIZE>& price);
            // or just
            // friend std::ostream& operator<< <> (std::ostream& os ,const FixedPoint& price);
            ...
};

// definition
template<class T,unsigned int SIZE>
inline std::ostream& operator<<(std::ostream& os ,const FixedPoint<T,SIZE>& price){
    os << price.dollars << "." << price.cents;
    return os;
}

您可以在 class 模板本身中定义 friend 成员函数,

template<class T = int, unsigned int SIZE =2>
class FixedPoint {
  public:
      /* ... */

      friend std::ostream& operator<<(std::ostream& os ,const FixedPoint& price)
      {
          return os << price.dollars << "." << price.cents;
      }

      /* ... */
};