Saturday, August 16, 2014

C++11 – New Enumeration Class

With original implementation of C/C++ enumerations (enum), I preferred to add a suffix to each of the enumerators to associate them to the enumeration so that when one appears in the code, it is easy to identify it to the enumeration:
enum EnumName {
    First_EnumName,
    Second_EnumName,
    Third_EnumName
};
Without this suffix, it is difficult to see which enumeration the value is associated to.  (Though using an IDE like Qt Creator, there is a command to go right to the definition.)  In addition, obviously the same name can't be used for two different enumerations.  A suffix (a prefix could have been used instead) solves this issue.

C++11 introduces a new enum class where the enumerators are scoped inside the enumeration.  The enumerators for these are also more strongly typed then the normal enumerations (which represent integers and can be used as such).  As an enumeration class, the above enumeration becomes:
enum class EnumName {
    First,
    Second,
    Third
};
In order to use these enumerations, they must be scoped, so to refer to the second enumerator, the name EnumName::Second would be used.  This is similar to my solution of using suffix (in this case it is a prefix).  An example of an enumeration class was added to the try compile test program.  The intention is to change the enumerations used in the project to enumeration classes.

[branch cpp11 commit 2a8e3899ee]

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.)