rational: add invert, inverse, div, and mul

This commit is contained in:
Danny Robson 2014-10-20 12:56:28 +11:00
parent 3fd3b805af
commit 9ffaa5782b
2 changed files with 52 additions and 0 deletions

View File

@ -54,8 +54,50 @@ rational<T>::operator double (void) const {
}
//-----------------------------------------------------------------------------
template <typename T>
rational<T>::operator int (void) const {
return n / d;
}
//-----------------------------------------------------------------------------
template <typename T>
rational<T>
rational<T>::inverse (void) const {
return rational<T> { d, n };
}
//-----------------------------------------------------------------------------
template <typename T>
template <typename U>
rational<T>
rational<T>::operator* (const U &rhs) const {
return { rhs * n, d };
}
//-----------------------------------------------------------------------------
template <typename T>
template <typename U>
rational<T>
rational<T>::operator/ (const U &rhs) const {
return { n, rhs * d };
}
//-----------------------------------------------------------------------------
template <typename T, typename U>
rational<T>
util::operator/ (U lhs, rational<T> rhs) {
return rhs.inverse () * lhs;
}
//-----------------------------------------------------------------------------
namespace util {
template struct rational<uint32_t>;
template struct rational<int32_t>;
template rational<uint32_t> operator/ (int, rational<uint32_t>);
}

View File

@ -30,10 +30,20 @@ namespace util {
explicit operator float (void) const;
explicit operator double (void) const;
explicit operator int (void) const;
rational<T> inverse (void) const;
rational<T>& invert (void);
template <typename U> rational<T> operator* (const U&) const;
template <typename U> rational<T> operator/ (const U&) const;
T n;
T d;
};
template <typename T, typename U>
rational<T> operator/ (U, rational<T>);
}
#endif