Browse DevX
Sign up for e-mail newsletters from DevX


Simplify Callback Dispatching with Enumerated Indexes-3 : Page 3




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Enumerating Options
Using an enum for binding meaningful names to numeric values is an ideal solution to this problem. However, it has to be done carefully. The first step is to define an enumeration that lists all the possible operations:

enum mail_ops { send, reply, forward, delete };

Remember to leave all enumerators without an explicit initializer. This way, the compiler automatically assigns consecutive numbers to each enumerator starting with 0, i.e., send=0, reply=1 etc. Secondly, provide a final enumerator after all the valid operations:

enum mail_ops { send, reply, forward, delete, max_mail_ops //always should be the last };

Author's Note: I deliberately defined an independent enum for the operations instead of reusing enum Icons because there are icons for which class Mail doesn't define an operation, "Help" for instance. Furthermore, mail_ops adheres to stricter definition rules. Therefore, it's best to use separate enums for the icons and the operations.

The last enumerator contains the total number of operations, which is handy for declaring an array of callbacks:

mail_pmf options[max_mail_ops]= {&Mail::Send, &Mail::Reply, &Mail::Forward, &Mail::Delete};

This makes your code more resilient to changes. If, for example, you decide to add more operations:

enum mail_ops { send, reply, forward, delete, save, //newly added max_mail_ops };

max_mail_options will be adjusted automatically to 5, as would the number of elements in the array. Of course, the new elements must be initialized appropriately:

mail_pmf options[max_mail_ops]= {&Mail::Send, &Mail::Reply, &Mail::Forward, &Mail::Delete, &Mail::Save};

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date