Mark Oborne

Software Engineer

markoborne1@gmail.com

Scope-based enums

Scope-based enums were added in C++11 as a way to give the programmer greater control of how the enum is used. Something that can be extremely important when working on large projects or as part of a team.

Giving enums their own scope can prevent clashes with other enums. Imagine a program tracking fruits and their colours.

enum fruit{ apple, orange };

enum colour{ red, orange };

This wouldn't compile, however scope-based enums enforce more specificity with the scope resolution operator :: allowing you to have shared names among enums.

fruit::orange;

However, if the increased verbosity is hurting the readability of your code, C++20 is coming to the rescue with the ability to use the 'using' keyword with enum scopes as if they were namespaces.

An important part of standard enums is the fact that they can be implicitly converted to integers. Scoped enums however, can only be explicitly converted, which can help with a lot of issues. For example if you have overloaded operators where one takes an int and another takes an enum. Which function will be called? Ambiguity can be your worst nightmare as a programmer. That's why nullptr is prefered to NULL but that's a story for another blog.

To conclude, there's clearly many reasons to have scoped enums as your standard and I hope to see an increase in their use in the future.

Back