C ++中的模板类重载运算符ostream不起作用

问题描述

所以我有这个模板类:

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文件中类的定义

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&,SIZE>&)’ declares a non-template function

我尝试在脱模术中添加模板名称,但无法识别T类,所以我该怎么办?我应该为每种类型制作规格模板吗?

解决方法

如错误消息所述,friend声明声明了非模板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,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,SIZE>& price){
    os << price.dollars << "." << price.cents;
    return os;
}
,

您只需在类模板本身内定义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;
      }

      /* ... */
};