I am currently stuck on a problem that I can't solve. I am a beginner in the world of c++.
For a homework, I have to create a generic class to represent a fraction like 5/6 or 11/4. This class is generic which allows to determine the type of the nominator and numerator (unsigned short, unsigned, unsigned long).
The goal is to be able to add, subtract, multiply, divide and compare fractions. In a first phase, I created a class and operator overloads allowing me to do everything that is required but only for instances of the class with the same type.
Now I would like to improve the existing code to be able to perform operations between fractions of different types like for example: Frac<unsigned> == Frac<unsigned short>
. But there is something I don't understand in the syntax of overloading operators.
Let's take the == operator as an example:
template <typename T>
bool operator==(const Frac<T>& lhs, const Frac<T>& rhs) {
return (lhs.numerator == rhs.numerator && lhs.denominator == rhs.denominator);
}
template <typename T>
class Frac {
friend bool operator== <>(const Frac& lhs, const Frac& rhs);
private:
T numerator, denominator;
};
this is the current version that worked for the Fracs of the same type. But now I would like it to work for Fracs of a different type:
template <typename T>
class Frac;
template <typename T, typename U>
bool operator==(const Frac<T>& lhs, const Frac<U>& rhs){
return (lhs.numerator == rhs.numerator && lhs.denominator == rhs.denominator)
}
template <typename T>
class Frac {
friend bool operator== <>(const Frac& lhs, const Frac& rhs);
private:
T numerator, denominator;
};
But I have a compilation error when I want to compare Frac of different types... I don't understand and didn't find any solution explaining concretely what the problem was and how to implement this kind of solution properly.
Could you help me please ?
I hope my question is clear and complete.
You can do this the following way:
template <typename T>
class Frac {
//friend declaration
template <typename S, typename U> friend
bool operator==(const Frac<S>& lhs, const Frac<U>& rhs);
private:
T numerator, denominator;
};
template <typename T, typename U>
bool operator==(const Frac<T>& lhs, const Frac<U>& rhs){
return ((lhs.numerator == rhs.numerator) && (lhs.denominator == rhs.denominator));
}
Now you will be able to compare Frac
for different types as you want.