Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a generic Numeric class in C++

Tags:

c++

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.

like image 843
mmisu Avatar asked Mar 21 '12 17:03

mmisu


1 Answers

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;
}
like image 178
ApprenticeHacker Avatar answered Oct 03 '22 06:10

ApprenticeHacker