Imported Upstream version 15.19.0
[platform/upstream/libzypp.git] / zypp / base / EnumClass.h
index 9122c61..d7f2b1a 100644 (file)
@@ -25,28 +25,54 @@ namespace zypp
     /// \class EnumClass
     /// \brief Type safe enum (workaround SWIG not supporting enum class)
     /// \code
-    /// struct _ColorDef { enum Enum { R, G ,B }; }
-    /// typedef EnumClass<_ColorDef> Color;
+    /// struct EColorDef { enum Enum { R, G ,B }; };
+    /// typedef EnumClass<EColorDef> Color;
+    /// \endcode
+    /// Conversion to from string can be easily added, e.g. like this:
+    /// \code
+    /// struct EColorDef {
+    ///   enum Enum { R, G ,B };
+    ///   static Enum fromString( const std::string & val_r );
+    ///   static const std::string & asString( Enum val_r );
+    /// };
+    /// std::ostream & operator<<( std::ostream & str, const EColorDef & obj )
+    /// { return str << EColorDef::asString( obj.inSwitch() ); }
+    ///
+    /// typedef EnumClass<EColorDef> Color;
+    /// Color red = Color::fromString("red");
+    /// cout << red << endl; // "red"
     /// \endcode
     ///////////////////////////////////////////////////////////////////
-    template<typename _EnumDef>
-    class EnumClass : public _EnumDef
+    template<typename TEnumDef>
+    class EnumClass : public TEnumDef
     {
     public:
-      typedef typename _EnumDef::Enum Enum;    ///< The underlying enum type
+      typedef typename TEnumDef::Enum Enum;            ///< The underlying enum type
+      typedef typename std::underlying_type<Enum>::type Integral;///< The underlying integral type
 
       EnumClass( Enum val_r ) : _val( val_r ) {}
 
-      /** For use in switch
+      /** Underlying enum value for use in switch
        * \code
-       * struct _ColorDef { enum Enum { R, G ,B }; }
-       * typedef EnumClass<_ColorDef> Color;
+       * struct EColorDef { enum Enum { R, G ,B }; }
+       * typedef EnumClass<EColorDef> Color;
        *
        * Color a;
-       * switch ( a.inSwitch() )
+       * switch ( a.asEnum() )
        * \endcode
        */
-      Enum inSwitch() const { return _val; }
+      Enum asEnum() const { return _val; }
+
+      /** Underlying integral value (e.g. array index)
+       * \code
+       * struct EColorDef { enum Enum { R, G ,B }; }
+       * typedef EnumClass<EColorDef> Color;
+       *
+       * Color a;
+       * std::string table[] = { "red", "green", "blue" };
+       * std::cout << table[a.asIntegral()] << std::endl;
+       */
+      Integral asIntegral() const { return static_cast<Integral>(_val); }
 
       friend bool operator==( const EnumClass & lhs, const EnumClass & rhs ) { return lhs._val == rhs._val; }
       friend bool operator!=( const EnumClass & lhs, const EnumClass & rhs ) { return lhs._val != rhs._val; }