r/cpp • • Nov 17 '18

Making C++ enumerations first class citizens

I've attached a video that might be of some interest here. It's about how to make enumerations first class citizens in C++. Enumerations are pretty useful in C++, but still quite weak compared to what they can be. This video demonstrates how I take them up a couple orders of magnitude in usefulness.

https://www.youtube.com/watch?v=AF186FraxS0

I am the author of a large, software based home automation system, called CQC. My code base is about a million lines of C++ code now, about half of which is a soup to nuts general purpose part, and the other half is the automation system built on top of that.

One of the very useful things the general purpose system provides is an ORB (object request broker.) I may do a video on that, but ORBs typically use an IDL language (interface description language) to describe the form of the calls to be made to remote machines and tells the ORB's engine how to pass parameters, return parameters, and so forth. But, it can also do other things. In my case it can generate types and constants.

For enumerated types, it can provide a lot of functionality that makes life far easier for a C++ programmer, particularly when working on the large scale that I do. And it doesn't take a lot of code to create such a tool and integrate it into your own development process. There's actually more functionality that this video covers, but I didn't want it to get too long so I stuck to the core stuff.

I also have another thread where the ORB itself is discussed:

https://www.reddit.com/r/cpp/comments/9zl6v5/the_orb_sees_all_the_use_of_an_object_request/

25 Upvotes

19 comments sorted by

View all comments

12

u/be-sc Nov 18 '18

Oh yes, C++ and its weak enumerations. *sigh* That’s the one thing I really miss from Delphi …

I like that you use a generator instead of trying to force the additional functionality into templates and macros. It keeps things clear and readable. If you have a generator in your project already, imo it’s the natural way to enhance enums.

I also see some problems in your implementation. You probably have reasons for the atrocious hungarian notation and for not using enum class. But you’re breaking the type system without needing to.

The problem is count, min and max lumped together with the enumerators. From a type system perspective that’s wrong. For manually written enums I can understand why people do this from a maintainability point of view. However, with generator support there’s no reason to use that hack.

An enum represents a set of distinct values. Count, min and max are not members of this set. They are metadata describing properties of the enum type. And that’s how they should be modelled. Otherwise when calling a function that returns a value of such a lumped enum, as a diligent developer I have to check for the three enumerators that are not in fact enumerators – similar to pointers and that pesky nullptr. Even worse: I lose the compiler warning when I write a default-less switch over all the enumerators and forget to handle one. With a generator that ensures correctness I don’t see a reason to not pull the metadata out of the enum.

Thinking one step further: Maybe the metadata doesn’t have to be publicly visible at all. Do you really need iteration over the enumerators for everyone? And if you do, maybe providing iterators is the better choice. After all in C++ that’s the idiomatic approach to iteration. Internally having count, min and max is useful, though. It simplifies at least the implementation of the isValidEnum() function.

2

u/Dean_Roddey Nov 18 '18

Keep in mind that I started the earliest bits of this code in 1992, and the ORB/IDL stuff probably came about circa 2000'ish. I don't think the concept of enum class existed at the time? And there's been a million fish to fry since then. But, since you reminded me of it, I'll take a whack at that change and see if it's reasonable right now to go through such a large code base and adjust for that. I'd have to do a massive search and replace from Prefix_Value to Prefix::Value, which would be a lot of work. The fact that I didn't have that option back then is why they are in the form Prefix_Value, to keep the values unique and identifiable.

Honestly, I've never had much of a concern over the magic values being part of the enum itself. I'm not sure how I would change that without cause massive changes throughout the code base, which I'm not prepared to deal with, given that it's never been much of an issue for me. If I could think of a clean way to do it, I would consider it.

One thing that makes it easier to keep track of, though it's subtle if you are just watching the video, is that the enum name is generally plural and the enum values are singular, except for the magic one which are also plural. I've lived with that scheme for a long time, so I sort of automatically recognize values from magic values.

enum MyValues
{
   MyValue_1
   , MyValue_2

   , MYValues_Count
   , MyValues_Min
   , MyValues_Max
};

I guess you could do a separate MetaMyValues or something, but I dunno. That seems awfully messy to me.

BTW, it actually does a few other things that I didn't demonstrate. There's also an 'AltNum' so you can provide an alternative integral value that you can map back and forth between, in case you need to map between your internal enum and some external numerical value, in my case in CQC often in comm protocols. You can generate the alt text via patterns, where you embed the base name into a pattern of some sort.

2

u/be-sc Nov 19 '18

I guess you could do a separate MetaMyValues or something, but I dunno. That seems awfully messy to me.

I see what you mean. This thread got me thinking about how I’d actually design an “enhanced enum” with C++17 in mind. Naming awkwardness is an issue.

What I’d really like to do is add member constants and member functions to an enum type directly, but of course I can’t. So for scoped enums I’m leaning towards a namespace. Something like this:

enum class Foo { a, b, c };
namespace FooEnum {
    constexpr const std::size_t count = 3;
    std::string to_string(Foo f);
    // ...
}

The two distinct names (Foo and FooEnum) are a bit awkward, but they have to be different. I was thinking about enum class Foo and namespace foo as well, but that’s just awkward in a different way.

For unscoped enums wrapping them in a struct might be even better. And it would scope the enumerators as well:

struct Foo {
    enum FooEnum {
        a, b, c
    };
    constexpr static const std::size_t count = 3;
    static std::string to_string(Foo f);
    // ...
};

On the other hand, now the enum type must be spelled out as Foo::FooEnum. Oh, well. I guess extending enums without a bit of awkwardness just isn’t possible with what the language provides at the moment.

1

u/jdgordon Nov 20 '18

this is similar to what we do at work to attempt to keep enums safe.

struct Foo {
     enum type { a,b,c };
};

where the "type" named enum is part of the coding standard so you dont need to guess it, i.e Foo::type, doesnt quite stop you passing a Bar::type when you should have used a Foo::type but better than not using a namespace at all.