so i have this template 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;
};
and this is it's definition under the class in the h file
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;
}
the code gives me the following error:
friend declaration ‘std::ostream& operator<<(std::ostream&, const FixedPoint<T, SIZE>&)’ declares a non-template function
i tried adding the template name in the decleration but it doesn't recognise T class so what can i do? should i make specification templates for each type ?
As the error message said, the friend
declaration declares a non-template operator<<
, but it's defined as a template, they don't match.
You can make the friend
declaration referring to the operator template, e.g.
// 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;
}