C++ 98/C++11 enums

September 20, 2012

I am writing a cross-platform C++ library to read/write configuration files from/to multiple representation (JSON, XML, etc).  In a nushell, the configuration file is tree node based. Each node is represented as a SettingNodeInterface. Each Node has a type: OBJECT, ARRAY, VALUE, etc. I was wondering what would be the best way to represent this group of related values while keeping in mind the following constraints:

What are the possible solutions ?

Enums are a good choice. Let's see how one should go about it.

Possible Implementations

Solution 1

class SettingNodeInterface {
 public:
  /**
   * Types
   */
  enum Type {
   TYPE_UNDEFINED,         /** Undefined */
   TYPE_OBJECT,            /** Object */
   TYPE_ARRAY,             /** Array */
   TYPE_VALUE              /** Value */
  };
};

Solution  2

class SettingNodeInterface {
 public:
  class SettingNodeType { public:
   /**
    * Types
    */
   enum Type {
    UNDEFINED,     /** Undefined */
    OBJECT,            /** Object */
    ARRAY,             /** Array */
    VALUE             /** Value */
   };
  SettingNodeType(Type t) : t_(t) {}
  SettingNodeType() : t_(UNDEFINED) {}
  operator const Type() const { return t_;}
 private:
  Type t_;
 };
};

Solution 3

class SettingNodeInterface {
 public:
  struct SettingNodeType {
  enum Type {
   UNDEFINED,         /** Undefined */
   OBJECT,                /** Object */
   ARRAY,                 /** Array */
   VALUE                 /** Value
  };
};
};

I raised this problematic StackOverflow. There may be additional inputs over there if you are curious.

Conclusion

I picked Solution 1 for the following reasons:

Discussion, links, and tweets

I'm a developer at IO Stark.