C ++中的通用数字

generic number in c++

我想制作一个 BigInteger 对象(用于练习)。我希望重载运算符接受任何数字数据类型。我可以多态地做到这一点,但由于为 20~ 数字类型中的每一种重载 20 多个二元运算符是不切实际的,我真的很想做这样的事情:

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

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

抱歉,我的问题是:"is this possible"?

我昨晚的大部分时间都在研究这个问题,我通读了 cpp.com, the list of overloadable operators on wikipedia 上的运算符重载条目,以及关于堆栈溢出的各种帖子。

可能通过稍微不同的方式。参见示例:

#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();
}

为了完整起见,这里是输出:

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