Nest enum class or not?

Viewed 101

One can have standalone enum-classes:

enum class StreamOpenMode
{
    read,
    write,
    readWrite
};

class Stream
{
public:

    Stream(StreamOpenMode openMode)
    //...
};

Or nest them in another class:

class Stream
{
public:

    enum class OpenMode
    {
        read,
        write,
        readWrite
    };

    Stream(OpenMode openMode)
    //...
};

What are the technical reasons to choose one over the other? For example, the nested variety can't be forward declared, which might lead to circular dependency issues in large projects.

1 Answers

For example, the nested variety can't be forward declared, which might lead to circular dependency issues in large projects.

To be fair, that in itself is probably the strongest technical reason.

You'll also find that Argument-Dependent Lookup relies on the shared scope:

namespace N
{
   struct A
   {
      enum class B { aB };
      friend void f(B);
   };
}

void test(N::A::B x)
{
   f(x);  // f found by ADL, since x's type is a member of A
}

A different example may demonstrate a whole suite of classes similar to Stream, each with their own similar-but-different scoped enum. Having it as a member makes it a little easier to use said scoped enum from the context of a template (T::OpenMode!). But, in that scenario, member type aliases would make it pretty trivial to keep the scoped enum outside of the class.

Related