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;
I don't think that it is possible. You can achieve something similar using templates:
template<typename T>
class frac_template
{
public:
T numerator;
unsigned int denominator;
};
class frac : public frac_template<int> {};
class ufrac : public frac_template<unsigned int> {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With