S
Simon Elliott
What operators can be used to extend an enum?
Can I extend an enum with an operator= and if so what's the syntax?
Can I extend an enum with an operator= and if so what's the syntax?
Simon Elliott said:What operators can be used to extend an enum?
What do you mean by "extend and enum"?
Simon said:For example:
enum garden_veg {CARROT=0x01,TURNIP=0x02,PARSNIP=0x04,SPROUT=0x08};
garden_veg operator|(garden_veg lhs, garden_veg rhs)
{
return(garden_veg(lhs|rhs));
}
...
garden_veg ct = CARROT|TURNIP;
I've seen operator|, operator&, and (postfix and prefix) operator++ and
operator--, but I haven't seen operator=.
You should probably have:
typedef unsigned int veg_mask;
Simon said:Yes, although this still has problems because veg_mask has no type
safety
Indeed.
> But short of wrapping the enum in a class I'm not sure there's
a better way.
The operator| was just an example to answer Rolf Magnus's question. As
per my original post, it's the operator= I'm really interested in.
Ben said:Well, you can't override the operators of an int or enum, you'll have to
use your own type (class/struct).
Ben said:When initialising an enum from an int, you need to cast:
garden_veg v(static_cast<garden_veg>(CARROT|TURNIP));
The value in v is now undefined (it might be 1, 2, 3 or anything else),
since it doesn't represent any value of garden_veg.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.