Skip to content

enum class in C++11

I’ve opened the new edition of Cuboid Stroustrup exactly once, and I’ve already learned exactly one useful thing.

Before going into what that thing was, a comment on the book: The C++ Programming Language is, along with Object-Oriented Software Construction by Bertrand Meyer, one of the best books on a programming language I’ve ever read. In addition to explaining the language and its features, they explain why it is as designed. You get to find out how the various features are expected to be used: a great introduction to the idioms adopted by its community.

Conversely, Object-Oriented Programming: An Evolutionary Approach discusses much of the philosophy without going into much depth on the language itself. The C Programming Language goes the other way, explaining the language in detail without describing why any of its features were designed the way they were, or how you mighty want to put them together. It also happens that both of these books are too old to learn modern idiomatic use of their languages from.

Anyway, enum class. The problems with C enum are twofold: firstly the named values go into the global namespace so you can’t duplicate names (imagine if you wanted to have text alignment and view content mode enumerations, for example, you couldn’t use “Left” and “Right” as names in both places). Secondly, the values are just integers, so nonsense expressions like Left + Right are possible. What C++ has added recently is strongly typed, namespaced enum classes:

enum class TextAlignment { Left, Right };

You can’t do silly things like add these together, because TextAlignment is a custom type so it can’t be treated as an integer. You’d have to overload operator+() before addition could work—meaning you’d need a reason to do it. This is something I’ve long wanted in Objective-C, though my expectation is that Objective-C enumerations would be Flyweight Objective-C objects:

An Objective-C specific @enum type, which creates static, immutable instances. So you could have:

@enum GLScreenOrientation {Landscape, Portrait};

which creates a class like this:

@interface GLScreenOrientation: NSObject <NSCopying>
+ (GLScreenOrientation *)Landscape;
+ (GLScreenOrientation *)Portrait;
+ (NSSet *)values;
@end

This is modelled after the Java enum.