let’s say I have this:
enum E{
a,
b,
c,
total
}
class A {
char mask; // supposed to contains combinations of values of the enum, like a or c, etc
}
Is there a decent solution to build the object A in a user-friendly way?
For instance I could do:
A(E e) {
mask = 1 << e;
}
but this will only work if you want the mask to be made from only 1 element of the enum
Ideally the user would be able to do something like :
A* a = new A(a | c)
and this would automatically create
mask = 1 << a | 1 << c;
Any idea on how to do this correctly?
thanks
edit
sadly I have no control over the initial enum and the values are increasing 1 by 1
Well, there’s the simple way and the ugly way.
The simple way is to define the bits as non-overlapping to being with, e.g.:
The ugly way:
where
E_helperis a class that overridesoperator|(enum E).And then your user can say
which expands to
which causes this chain of events
Better yet, move the
.get()call inside A’s constructor, which then takes an argument of typeA_helper. This will let you catch the case where the user forgot to use theMAKEAmacro.Be warned, however, that the ugly way exposes counter-intuitive behavior. For example,
A* p = MAKEA(a | c);is different fromA* p = MAKEA( (a | c) );andchar mask = a | c; A* p = MAKEA(mask);