EnumTraits.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 #ifndef __ccxx_EnumTraits_hxx
00024 #define __ccxx_EnumTraits_hxx
00025
00026 #include <commonc++/Common.h++>
00027 #include <commonc++/CharTraits.h++>
00028
00029 #include <utility>
00030 #include <vector>
00031
00032 namespace ccxx {
00033
00042 template<typename E> class EnumTraits
00043 {
00044 public:
00045
00047 static E min();
00048
00050 static E max();
00051
00053 static E defval();
00054 };
00055
00066 template<typename T, typename E> E enum_cast(T val)
00067 {
00068 if((val >= static_cast<T>(EnumTraits<E>::min()))
00069 && (val <= static_cast<T>(EnumTraits<E>::max())))
00070 return static_cast<E>(val);
00071 else
00072 return EnumTraits<E>::defval();
00073 }
00074
00086 template<typename T, typename E> E enum_cast(T val, E defval)
00087 {
00088 if((val >= static_cast<T>(EnumTraits<E>::min()))
00089 && (val <= static_cast<T>(EnumTraits<E>::max())))
00090 return static_cast<E>(val);
00091 else
00092 return defval;
00093 }
00094
00109 template<typename E> class EnumMap
00110 : private std::vector<std::pair<E, const char *> >
00111 {
00112 public:
00113
00115 EnumMap() { }
00116
00118 ~EnumMap() { }
00119
00121 EnumMap& add(E value, const char *str)
00122 {
00123 this->push_back(make_pair(value, str));
00124 return(*this);
00125 }
00126
00133 E valueForString(const char *str) const
00134 {
00135 for(typename Entries::const_iterator iter = this->begin();
00136 iter != this->end();
00137 ++iter)
00138 {
00139 if(CharTraits::compare(str, this->second))
00140 return(this->first);
00141 }
00142
00143 return(EnumTraits<E>::defval());
00144 }
00145
00152 const char *stringForValue(E value) const
00153 {
00154 for(typename Entries::const_iterator iter = this->begin();
00155 iter != this->end();
00156 ++iter)
00157 {
00158 if(value == iter->first)
00159 return(this->second);
00160 }
00161
00162 return(NULL);
00163 }
00164
00165 private:
00166
00167 typedef std::vector<std::pair<E, const char *> > Entries;
00168 };
00169
00170 };
00171
00172 #endif // __ccxx_EnumTraits_hxx
00173
00174