0

I have a problem with my c++ program.

I created a class that represents modulo number.

Let's say it looks like:

template <typename Type> class Cycler
{
    public:
        Cycler(Type Mod) : CurrentIndex(0), Mod(Mod)
        {}

        Cycler & operator ++ ()
        {
            F();
            return *this;
        }
        Type operator ++ (int)
        {
            F();
            return CurrentIndex;
        }
        Cycler & operator -- ()
        {
            B();
            return *this;
        }
        Type operator -- (int)
        {
            B();
            return CurrentIndex;
        }
        operator Type()
        {
            return CurrentIndex;
        }
    protected:
        void F()
        {
            if((++CurrentIndex) == Mod)
                CurrentIndex = 0;
        }
        void B()
        {
            if(CurrentIndex == 0)
                CurrentIndex = Mod - 1;
            else
                CurrentIndex--;
        }
        Type CurrentIndex, Mod;
};

But let's say I'm doing:

Cycler<unsigned int> C(100);
unsigned int I1 = C; // IS 0, OK
I1 = ++C; //Is 1 - OK
I2 = C++; //Is 2 - NOT OK

If i do:

...
I2 = C;
C++;

//It is ok

I think this is a problem with oreder of operators executed - my number is incremented after ++, but before being casted to unsigned int.

How can I make this work?

peku33
  • 3,628
  • 3
  • 26
  • 44
  • See [this post](http://stackoverflow.com/questions/4421706/operator-overloading/4421719#4421719) for operator overloading techniques. – chris May 07 '14 at 12:27

1 Answers1

1

Normally you implement the post-increment operator by saying:

    Cycler operator ++ (int)
    {
        Cycler tmp = *this;
        F();
        return tmp;
    }

Post-increment and post-decrement operators normally return the object as it was before the increment/decrement. Thus they have to create a copy of the original state of the object before alteration.


Btw, arithmetic for unsigned types is slightly different than for signed types. unsigned integers are defined to wrap around. For example if you have an unsigned char, 255+1 is 0 again. Same for 0-1 = 255. This is not undefined behavior as opposed to signed integers!

So in your case you can just simplify F() to i = (i+1) % n and B() to i = (i-1) % n.

Danvil
  • 22,240
  • 19
  • 65
  • 88