所以我有这个模板类:
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&, const FixedPoint<T, 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 ,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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句