Enum.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00030 #ifndef _GG_Enum_h_
00031 #define _GG_Enum_h_
00032
00033 #include <boost/config.hpp>
00034
00035 #include <map>
00036 #include <string>
00037
00038
00039 namespace GG {
00040
00042 struct EnumMapBase
00043 {
00044 BOOST_STATIC_CONSTANT(long int, BAD_VALUE = -5000000);
00045
00046 virtual ~EnumMapBase() {}
00047
00050 virtual const std::string& FromEnum(long int i) const = 0;
00051
00054 virtual long int FromString (const std::string& str) const = 0;
00055 };
00056
00062 template <class E> struct EnumMap : EnumMapBase
00063 {
00064 virtual ~EnumMap() {}
00065 virtual const std::string& FromEnum(long int) const
00066 { static std::string empty; return empty; }
00067 virtual long int FromString (const std::string&) const {return 0;}
00068 };
00069
00072 template <class E> EnumMap<E> GetEnumMap()
00073 {
00074 static EnumMap<E> enum_map;
00075 return enum_map;
00076 }
00077
00088 #define GG_ENUM_MAP_BEGIN( name ) \
00089 template <> struct EnumMap< name > : EnumMapBase \
00090 { \
00091 typedef name EnumType; \
00092 typedef std::map<EnumType, std::string> MapType; \
00093 EnumMap () \
00094 {
00095
00098 #define GG_ENUM_MAP_INSERT( value ) m_map[ value ] = #value ;
00099
00102 #define GG_ENUM_MAP_END \
00103 } \
00104 virtual const std::string& FromEnum(long int i) const \
00105 { \
00106 static const std::string ERROR_STR; \
00107 std::map<EnumType, std::string>::const_iterator it = \
00108 m_map.find(EnumType(i)); \
00109 return it == m_map.end() ? ERROR_STR : it->second; \
00110 } \
00111 long int FromString (const std::string &str) const \
00112 { \
00113 for (MapType::const_iterator it = m_map.begin(); \
00114 it != m_map.end(); \
00115 ++it) { \
00116 if (it->second == str) \
00117 return it->first; \
00118 } \
00119 return BAD_VALUE; \
00120 } \
00121 MapType m_map; \
00122 };
00123
00126 #define GG_ENUM_STREAM_IN( name ) \
00127 inline std::istream& operator>>(std::istream& is, name& v) \
00128 { \
00129 std::string str; \
00130 is >> str; \
00131 v = name (GG::GetEnumMap< name >().FromString(str)); \
00132 return is; \
00133 }
00134
00137 #define GG_ENUM_STREAM_OUT( name ) \
00138 inline std::ostream& operator<<(std::ostream& os, name v) \
00139 { \
00140 os << GG::GetEnumMap< name >().FromEnum(v); \
00141 return os; \
00142 }
00143
00144 }
00145
00146 #endif // _GG_Enum_h_