Dominik Ficek
Dominik Ficek

Reputation: 566

Looking for any way to increment ENUM type without operator overloading

so this is about an assignment.

I have a header file with predefined ENUM type (TDay) which I CANNOT change in any way. TDay does not support any operator other than streams.

My problem is I need to find a way to do something like this:

Object::Object (uint aSize) {
    Object temp; // contains varible inicialized to zero, this variable can be bool, int, RGB structure 
                 // or TDay enum. I also can't use templates here.
    for (int i = 0; i < aSize; i++) {
        this->array[i] = temp.Value() + 1; // array is of the same type as Value
    }
}

This code is just for illustration of what I need to do, don't look for any use of this I just made it up just to better explain my problem.

So anyway this doesn't work because my TDay doesn't support TDay+int operator.

Is there any way around this? Solution doesn't have to be clean, I'll accept any pointer cheats.

EDIT:

So I tried putting in my Object.cpp file this:

TDay operator+(TDay aDay, int aValue) {
    return static_cast<TDay>(int(aDay) + aValue);
}

And it doesn't work. Compiler error says:

Argument of type int is imcompatible with parameter of type TDay

However if I put this code to TDay.h it works fine. Is something wrong with my linker?

Upvotes: 0

Views: 186

Answers (1)

Hawky
Hawky

Reputation: 440

I would create a function taking current ENUM value named for example increase

void increase(your_enum& e){
    if(e == e::MAX_VAL)
        e = e::MIN_VAL; //if you have it, otherwise do same as below
    else{
        int val = int(e); //cast it to int
        val++;
        e = static_cast<your_enum>(val); //cast it back
    }
}

Creating a function taking another parameter to increase/decrease by more than one should be easy from this point.

Upvotes: 1

Related Questions