What is the best approach to create a generic Numeric class in C++ ? I'm thinking at an object that can contain integers, floats and doubles.
My first idea is to use a union that will be used in a Numeric class where you can define the allowed operations for each type. Something like:
union mixed_number{
int a;
float b;
double c;
};
class Number{
//define operations
...
};
Please let me know if there is a better approach.
I made a generic Numeric class a while ago. Here:
template< typename T> class TypeWrapper
{
T value;
public:
TypeWrapper(T v): value(v) {}
operator T() { return value; }
// basic arithmetic operators
void operator = (T v){ value = v; }
TypeWrapper operator + (T v) { return TypeWrapper( value + v ); }
TypeWrapper operator - (T v) { return TypeWrapper( value - v); }
TypeWrapper operator * (T v) { return TypeWrapper( value * v); }
TypeWrapper operator / (T v) { return TypeWrapper( value / v); }
TypeWrapper operator % (T v) { return TypeWrapper( value % v); }
void operator += (T v) { value += v; }
void operator -= (T v) { value -= v; }
void operator *= (T v) { value *= v; }
void operator /= (T v) { value /= v; }
void operator %= (T v) { value %= v; }
T operator ++ () { return ++value; }
T operator -- () { return --value;}
T operator ++ (int v) { return value++; }
T operator -- (int v) { return value--; }
// conditions
bool operator == (T v) { return value == v; }
bool operator != (T v) { return value != v; }
bool operator > (T v) { return value > v; }
bool operator < (T v) { return value < v; }
bool operator >= (T v) { return value >= v; }
bool operator <= (T v) { return value <= v; }
T toPrimitive() { return value; }
string toString()
{
stringstream ss;
string rtn;
ss << value;
ss >> rtn;
return rtn;
}
};
// just to make things easier for a future move.
#define NumericTypeWrapper TypeWrapper
typedef NumericTypeWrapper< int > Integer;
typedef NumericTypeWrapper< double > Double;
typedef NumericTypeWrapper< float > Float;
}
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