Search code examples
c++operator-overloadingprimitive

generic number in c++


I want to make a BigInteger object (for practice). I want the overloaded operators to accept any numerical datatype. I can do this polymorphically, but since it would be impractical to overload the 20+ binary operators for each of the 20~ numerical types, I would really like to do something like this:

X & operator+(const anynum input)
{
  return this->value += input;
}

...
main()
{
  X a = 1;
  a = a + 1;
  a = a + 1L;
}

sorry, my question is: "is this possible"?

I researched this most of last night I read through the operator overloading entry on cpp.com, the list of overloadable operators on wikipedia, various posts on stack overflow.


Solution

  • Possible through slightly different means. See example:

    #include <iostream>
    
    class X
    {
    public:
        X(int val) :
                value(val)
        {
    
        }
    // this is the important part
        template<class TYPE>
        X & operator+(TYPE input)
        {
            value += input; // just demonstrating with a simple int
                            // a real bignum will be significantly more complex
                            // and you may well find that one function does not fit all cases
                            // for your particular bignum implementation
            return *this;
        }
    // end of important part
        void print()
        {
            std::cout << value << std::endl;
        }
    private:
        int value; 
    };
    
    int main()
    {
        short s = 1;
        unsigned short us = 1;
        int i = 1;
        long l = 1;
        long long ll = 1;
        float f = 1.0;
        double d = 1.0;
        X a(1);
        a.print();
        a + 1; // templated function is automatically implemented by compiler 
               // for the data type in the call. Use all the data types you want. 
               // The compiler will make one for each one used. 
        a.print();
        a + 1L;
        a.print();
        a + 1.0;
        a.print();
        a + s;
        a.print();
        a + us;
        a.print();
        a + i;
        a.print();
        a + l;
        a.print();
        a + ll;
        a.print();
        a + f;
        a.print();
        a + d;
        a.print();
    //  a + "Hi!"; Ka BOOOOOM! Cant add a string to an integer
        a + 'A'; // it does, however, allow this through because math on characters
                 // is a time-honoured tradition.
        a.print();
    }
    

    For completeness, here's the output:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    76