I'm writing some object code for processing fractional data (as opposed to floating-point data), and so far have the following:
class frac {
public:
int numerator;
unsigned int denominator;
};
My question is:
How can I configure my class definition such that writing unsigned frac foo;
makes an object identical to frac foo;
, except int numerator;
would become unsigned int numerator;
?
Edit:
While ordinarily I'd just use a template (frac <unsigned>
), this code is going into a larger math API, and I'd prefer the final product to use the unsigned frac
syntax
Extension:
Many answers have stated that it is not possible to implement the unsigned frac
syntax, but does anyone know why not? Does the C++ compiler have some special processing rule that accommodates for the existing unsigned
types, or is there something else I'm missing?
You can achieve such things with Templates. For example
template <class Integral>
class frac {
public:
Integral numerator;
std::make_unsigned_t<Integral> denominator;
};
http://en.cppreference.com/w/cpp/types/make_unsigned
You can use this class like this:
frac<int> signed;
frac<unsigned> nonnegative;