C++ typecasting with bitwise assignement operation

Viewed 160

I haven't found a way to typecast where bitwise assignment operation (e.g. x |= y &z;) is involved.

Example:

#include <stdio.h>

typedef enum type1{
    AA = 0,
    BB = 1
} type1_e;

int main()
{

  type1_e x,y;

  y = type1_e(y | x); //working

  y |= (type1_e)(y|x); //ERROR: as.cc:15: error: invalid conversion from ‘int’ to ‘type1_e’

}
2 Answers

operator | yields an int result

type1_e(y | x)

y | x is an int. You're explicitly casting that int to type1_e.


y |= (type1_e)(y|x);

is equivalent to

y = y | type1_e(y | x);

You are using operator | which yields an int result, then trying to assign that to y which is type1_e. You can't do that without casting.


To overcome that, you could do this:

y = type1_e(y | type1_e(y | x));

which is the same as:

y = type1_e(y | y | x);

which is the same as:

y = type1_e(y | x);

or:

  y = static_cast<type1_e>(y | x);
  • You can write an overload for bitwise OR (|) that works for your enum.
  • You will have to use static_cast as well for proper conversion.

#include<iostream>
using namespace std;

typedef enum type1{
    AA = 0,
    BB = 1
} type1_e;

type1_e operator |=(type1_e& x, type1_e y)
{
    return x=static_cast<type1_e>(static_cast<int>(x) | static_cast<int>(y));
}


int main()
{
  type1_e x = AA, y = BB;
  y = type1_e(y | x); //working
  std::cout << y << '\n';

  x = AA, y = AA;
  y |= static_cast<type1_e>(y|x); //also works
  std::cout << y << '\n'; 

}

See demo.

Related