1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/base/EnumClass.h
11 #ifndef ZYPP_BASE_ENUMCLASS_H
12 #define ZYPP_BASE_ENUMCLASS_H
16 #include "zypp/base/PtrTypes.h"
18 ///////////////////////////////////////////////////////////////////
21 ///////////////////////////////////////////////////////////////////
24 ///////////////////////////////////////////////////////////////////
26 /// \brief Type safe enum (workaround SWIG not supporting enum class)
28 /// struct EColorDef { enum Enum { R, G ,B }; };
29 /// typedef EnumClass<EColorDef> Color;
31 /// Conversion to from string can be easily added, e.g. like this:
33 /// struct EColorDef {
34 /// enum Enum { R, G ,B };
35 /// static Enum fromString( const std::string & val_r );
36 /// static const std::string & asString( Enum val_r );
38 /// std::ostream & operator<<( std::ostream & str, const EColorDef & obj )
39 /// { return str << EColorDef::asString( obj.inSwitch() ); }
41 /// typedef EnumClass<EColorDef> Color;
42 /// Color red = Color::fromString("red");
43 /// cout << red << endl; // "red"
45 ///////////////////////////////////////////////////////////////////
46 template<typename TEnumDef>
47 class EnumClass : public TEnumDef
50 typedef typename TEnumDef::Enum Enum; ///< The underlying enum type
51 typedef typename std::underlying_type<Enum>::type Integral;///< The underlying integral type
53 EnumClass( Enum val_r ) : _val( val_r ) {}
55 /** Underlying enum value for use in switch
57 * struct EColorDef { enum Enum { R, G ,B }; }
58 * typedef EnumClass<EColorDef> Color;
61 * switch ( a.asEnum() )
64 Enum asEnum() const { return _val; }
66 /** Underlying integral value (e.g. array index)
68 * struct EColorDef { enum Enum { R, G ,B }; }
69 * typedef EnumClass<EColorDef> Color;
72 * std::string table[] = { "red", "green", "blue" };
73 * std::cout << table[a.asIntegral()] << std::endl;
75 Integral asIntegral() const { return static_cast<Integral>(_val); }
77 friend bool operator==( const EnumClass & lhs, const EnumClass & rhs ) { return lhs._val == rhs._val; }
78 friend bool operator!=( const EnumClass & lhs, const EnumClass & rhs ) { return lhs._val != rhs._val; }
79 friend bool operator< ( const EnumClass & lhs, const EnumClass & rhs ) { return lhs._val < rhs._val; }
80 friend bool operator<=( const EnumClass & lhs, const EnumClass & rhs ) { return lhs._val <= rhs._val; }
81 friend bool operator> ( const EnumClass & lhs, const EnumClass & rhs ) { return lhs._val > rhs._val; }
82 friend bool operator>=( const EnumClass & lhs, const EnumClass & rhs ) { return lhs._val >= rhs._val; }
88 ///////////////////////////////////////////////////////////////////
90 ///////////////////////////////////////////////////////////////////
91 #endif // ZYPP_BASE_ENUMCLASS_H