Mirror reflection library 0.5.13
|
00001 00010 #ifndef MIRROR_UTILS_ENUM_VAL_BY_NAME_1101180748_HPP 00011 #define MIRROR_UTILS_ENUM_VAL_BY_NAME_1101180748_HPP 00012 00013 #include <mirror/meta_enum.hpp> 00014 #include <map> 00015 #include <cstring> 00016 00017 MIRROR_NAMESPACE_BEGIN 00018 00020 template <typename Enum> 00021 class enum_value_by_name 00022 { 00023 private: 00024 struct ltcstr 00025 { 00026 bool operator()(const char* s1, const char* s2) const 00027 { 00028 return std::strcmp(s1, s2) < 0; 00029 } 00030 }; 00031 00032 template <typename ... Idx> 00033 static std::map<const char*, Enum, ltcstr> 00034 cache_vals_by_names(mp::range<Idx ...>) 00035 { 00036 return { 00037 std::pair<const char*, Enum>( 00038 mirror::_enum::_<Enum>::item_name(Idx()), 00039 mirror::_enum::_<Enum>::item_val_c(Idx()) 00040 )... 00041 }; 00042 } 00043 00044 static const std::map<const char*, Enum, ltcstr>& 00045 value_by_name_cache(void) 00046 { 00047 typename mp::make_index_seq< 00048 typename mirror::_enum::_<Enum>::item_count 00049 >::type indices; 00050 static auto cache = cache_vals_by_names(indices); 00051 return cache; 00052 } 00053 public: 00055 static bool has(const std::string& name) 00056 { 00057 auto pos = value_by_name_cache().find(name.c_str()); 00058 return (pos != value_by_name_cache().end()); 00059 } 00060 00062 00066 static Enum get(const std::string& name) 00067 { 00068 auto pos = value_by_name_cache().find(name.c_str()); 00069 assert(pos != value_by_name_cache().end()); 00070 return pos->second; 00071 } 00072 00074 00083 static std::pair<bool, Enum> get_opt(const std::string& name) 00084 { 00085 auto pos = value_by_name_cache().find(name.c_str()); 00086 if(pos == value_by_name_cache().end()) 00087 return std::pair<bool, Enum>(false, Enum()); 00088 return std::pair<bool, Enum>(true, pos->second); 00089 } 00090 }; 00091 00092 MIRROR_NAMESPACE_END 00093 00094 #endif //include guard 00095