advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
The beauty in enum types is that they're both high-level and very efficient. Are you contented with the current syntactic and semantics specifications of enum types in C++ or would you like to add more functionality to them? (for examples of such added functionality see the following proposal for adding enum types to Java). Let us know in our C++ Discussion Forum.
Partners & Affiliates
advertisement
advertisement
advertisement
advertisement
Average Rating: 3.3/5 | Rate this item | 9 users have rated this item.
Simplify Callback Dispatching with Enumerated Indexes (cont'd)
enums Will Save the Day
The most important contribution of this technique is in the event-dispatcher. Instead of using meaningless numbers as array indexes, you can now use mnemonic enumerators:

switch (icon_code)
{
case IC_Send:
dispatch(mail, options[send]);
break;
case IC_Reply:
dispatch(mail, options[reply]);
break;
case IC_Forward:
dispatch(mail, options[forward]);
break;
//..
case IC_Save:
dispatch(mail, options[save]);
break;
case IC_Help:
showOnlineHelp();
break;
}
advertisement
As a bonus, detecting typos is much easier now:

case IC_Save:
dispatch(mail, options[save]);
break;
case IC_Print:
dispatch(mail, options[save]);//a typo!
But That's Not All!
enum types offer two benefits over const int values: they automatically assign consecutive values to enumerators and they are strongly typed. Thus, if you declare a function that returns an enum:

mail_ops getUserClick();
The compiler can easily catch silly mistakes like this one:

mail_ops getUserClick()
{
return 20; //error
}
Some compilers are even clever enough to warn about missing enumerators in a switch statement.

Previous Page: Enumerating Options  
Danny Kalev is a system analyst and software engineer with 13 years of experience, specializing in C++ and object-oriented analysis and design. He is a member of the ANSI C++ standardization committee and the author of ANSI/ISO C++ Professional Programmer's Handbook (Que, 1999, ISBN: 0789720221). Reach him at dannykk@inter.net.il.
Page 1: IntroductionPage 3: Enumerating Options
Page 2: Demonstrating the ProblemPage 4: enums Will Save the Day
Please rate this item (5=best)
 1  2  3  4  5
advertisement