sergio campo
sergio campo

Reputation: 276

Overloading the tilde "~" operator for enums

Is it possible to define operators tilde ~ for enums? For example I have enum State in my example and I would like to be able to write result &= ~STATE_FAIL;. I did something like this:

#include <iostream>

    enum State
    {
        STATE_OK                     = 0x0,
        STATE_FAIL                   = 0x1,    
        STATE_LOW                    = 0x2,   
        STATE_HIGH                   = 0x4    
    };

    State & operator|=(State & a, const State b)
    {
        a = static_cast<State>(static_cast<int>(a) | static_cast<int>(b));
        return a;
    }

    State & operator&=(State & a, const State b)
    {
        a = static_cast<State>(static_cast<int>(a) & static_cast<int>(b));
        return a;
    }
     State & operator~(State& a)
    {
        a = static_cast<State>( ~static_cast<int>(a));
        return a;
    }


int main()
{
  State result = STATE_OK;

  result |= STATE_FAIL;    // ok
  result &= STATE_FAIL;    // ok
  result &= ~STATE_FAIL;    // fail

  return 0;
}

I get the following error:

In function int main(): Line 35: error: invalid conversion from int to State compilation terminated due to -Wfatal-errors.

Upvotes: 0

Views: 2444

Answers (1)

Emil Laine
Emil Laine

Reputation: 42838

The error you're getting is caused by taking the parameter as a non-const reference (which cannot bind to temporaries, which the expression STATE_FAIL is).

Also there's something wrong in your operator~ implementation: e.g. your operator~ modifies the parameter which is not the usual conventional behavior of ~, as shown here.

This should work in the expected way, i.e. it doesn't modify its argument and only returns the result of the operation:

State operator~(const State a)
{
    return static_cast<State>(~static_cast<int>(a));
}

Upvotes: 3

Related Questions