Saturday, August 16, 2014

Enumerators As Indexes – Using A Map

The first enumeration that will be changed to an enumeration class will be the data type enumeration.  One of the differences with enumerations is that unscoped enumerators can be used as integers.  One of the other things I preferred to do when defining an enumeration was add a size of enumerator at the end:
enum EnumName {
    First_EnumName,
    Second_EnumName,
    Third_EnumName,
    sizeof_EnumName
};
This size of enumerator can then be used to dimension an array, like to hold a conversion to another value (another enumeration, string, etc.).  This will not work with enumeration classes because the enumerators can't be used as integers without resorting to kludgy type casting (something I prefer to avoid if possible).  Plus, once this size of enumerator is added, then any switch statement using the enumeration will generate a warning since there is no case statement for this enumerator.  Adding a blank default statement is also kludgy.

Alternatively, using an associated array (map) instead of a C style array solves the issue of needing to know the size of the enumeration.  Compare the array solution to the map solution:
QString names[sizeof_EnumName] = {    QMap<EnumName, QString> names;
    "First",                          names[First_EnumName] = "First";
    "Second",                         names[Second_EnumName] = "Second";
    "Third"                           names[Third_EnumName] = "Third";
};
The array method is error-prone and care must be taken to make sure the right values (strings in this case) are applied to the right elements in the array.  This could be solved by using assignments that would look identical to the map assignments, though may not be as efficient because the assignments are done at run-time instead of at compile time, and the array still needs to be dimensioned.

The map method method of using assignments (same for the array method using assignments) can also be error-prone because it is easy to miss an assignment of one of the values.  In the array case, a null pointer would be returned, which will probably cause a segmentation fault unless it is checked for.

For the map method, however, accessing a value that doesn't exist simply adds a new element to the map with a default value (in this case a blank string).  This is still a problem, but much less fatal.  Alternatively, in the case of QMap, the value method function could be used instead of the [] operator, which doesn't add an element for a non-existing element and allows a default value to be returned for the non-existing element (for example, in this case a default value like "BUG" could be used).

No comments:

Post a Comment

All comments and feedback welcomed, whether positive or negative.
(Anonymous comments are allowed, but comments with URL links or unrelated comments will be removed.)