enum A
{
A0 = 0;
A1 = 1;
};
I want to make it so I can bitwise OR them like
A aVar1 = A0;
A aVar2 = A1;
aVar1 |= aVar2;
Is that possible? If so, how would I do it? Almost all examples seem to deal with classes and adding their variables.
enum A
{
A0 = 0;
A1 = 1;
};
I want to make it so I can bitwise OR them like
A aVar1 = A0;
A aVar2 = A1;
aVar1 |= aVar2;
Is that possible? If so, how would I do it? Almost all examples seem to deal with classes and adding their variables.
Quote:Original post by SiCrane
In what language?
Quote:Original post by tivolo
You can overload operators for enums in C++, if that's what you want.
Take a look here:
http://www.java2s.com/Tutorial/Cpp/0200__Operator-Overloading/Overloadingoperatorsforenumerations.htm
Quote:Original post by samoth
If this is C++, you'll run into trouble because two enums or-ed together are an integer, but not an enum. So... without nasty code (involving reinterpret_cast in overloaded operators) you'll probably not be able to do it.
class A { int value; A(int value): value(value) {} public: bool operator==(const A& other) { return value == other.value; } A operator|(const A& other) { return A(value | other.value); } A operator&(const A& other) { return A(value & other.value); } // The "safe bool" idiom doesn't work here because we *do* have a meaningful // comparison for equality (although maybe we want to ensure operator< etc. // don't compile). So I've just done the simplest thing. operator bool() { return value != 0; } static A foo, bar;};A A::foo(1 << 0);A A::bar(1 << 1);// ...bool some_func(const A& flags) { return flags | A::foo;}// ...some_func(A::foo | A::bar);
#include <iostream>enum Bits { left = 1 << 0, right = 1 << 1, both = left | right };const Bits& operator|=(Bits& lhv, Bits rhv){ lhv = static_cast<Bits>(lhv | rhv); return lhv;}int main(){ Bits a = left, b = right; a |= b; std::cout << a << '\n';}
Quote:Original post by visitorIf you just want bits to represent flags, you'd make an enum defining names for 1, 2, 4, 8, ..., but then use something like an unsigned to represent combinations of these flags.