TITLE: extending enumerators (Newsgroups: comp.lang.c++.moderated, 12 Mar 98) NORDELL: Mike Nordell >> When you want to merge two bits from some macro's or enum's that >> designate flags containing one set bit, your funtions always have to >> take an 'int', and all what we are used to call type safety is lost. DEROCCO: "Paul D. DeRocco" >I've wondered this myself. Can anyone involved in the standards process >explain why enums don't define the usual arithmetic operations, or at >least the bitwise logical ops? Obviously if an enum is used in its purest >sense, it shouldn't define arithmetic, as something like SundayöMonday is >pretty meaningless. However, enums are frequently used for constants that >are supposed to be ORed together. CLAMAGE: clamage@Eng.Sun.COM (Steve Clamage) If you want to use enums as other than typed manifest constants you can, but you may have to define your own arithmetic operators. Nordell gets his wish, however. Unlike C, C++ defines the valid range of an enum type to include all values that can be represented in the number of bits required to express the range of enumerators. In particular, you are assured that you can form the bitwise OR of all the enumerators, and the result will be a valid value for the enum type. Contrariwise, an int might not be big enough if long is bigger than int, because an enum value is not limited to the range of type int. So you could write enum E { e0=1, e1=2, e2=4, e3=8, e4=16 }; void foo(E); void f() { foo( E(e1|e2|e4) ); // always safe } Or you could define an overloaded operator| that takes and returns type E, and not need the cast. The extended range of the enum type allows you also to add new enum values without modifying the enum type definition. Example: enum spiciness { bland=0, mild=100, medium=500, hot=1000, AiAiAi=5000 }; It takes 13 bits to reperesent all the values from 0 through 5000, so type spiciness is guaranteed to be able to hold all values from 0 through 8191. You could define new values like this: const spiciness milder = spiciness(mild-20); const spiciness med_hot = spiciness((medium+hot)/2); const spiciness lethal = spiciness(8000); Now you can use med_hot as if it were an enumerator of type spiciness.