HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

C++ enums - which one is better?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
whichenumsonebetter

Problem

I have a large namespace, but I don't want enum constants to be a part of it. In cases where an enum is related with a class, I coded enums inside the class so I can reach it using the class name. However, if an enum is related with namespace functions, what is the best way to do it?

-
Use another namespace and put the enum inside, so from the outside it will be the same as others with different implementations?

-
Continue and create a class with private constructors so it will be as same as others?

Classes:

class A {
public:
   enum Type {
      Aa,
      Ab
   };

   Type GetType();
};

class B {
public:
   enum Type {
      Ba,
      Bb
   };

private:
   B();
};

B::Type DoSomething();


Namespace:

namespace B {
   enum Type {
       Ba,
      Bb
   };
}

B::Type DoSomething();


The first case seems to abuse classes, but it can be extended later to use same coding method as the others. I am in favor of namespace, but what are your opinions?

Solution

Do not use "enum in class" for public usage. You should use namespace for the purpose. (If your compiler supports C++0x, then use enum class.)

The problem with "enum in wrapper class" is header dependency. When declaration code wants to use some "enum in wrapper class" type, then it should also references the whole class information. Because you cannot physically separate enumeration from the wrapper class (one definition rule), it'll introduces heavier header dependency.

Moreover, because in C++, there can't be two separate definitions for one class so you cannot use forward declaration technique with "enum in wrapper class" like below.

// a.h
namespace A {
  enum Type {
    a,
    b
  };
}

// b.h
namespace A {
  enum Type; // forward declaration
}
A::Type function();

Code Snippets

// a.h
namespace A {
  enum Type {
    a,
    b
  };
}

// b.h
namespace A {
  enum Type; // forward declaration
}
A::Type function();

Context

StackExchange Code Review Q#3617, answer score: 9

Revisions (0)

No revisions yet.