c++ - most elegant way to hardcode pair, triplet ... values -
i have enum.
and each value in enum, need associate data (actually in case, it's integer, know more generally, instance 2 integer values, or 2 strings etc).
those values can't accessible user. in case of reverse engineering, well, can't much, should ask user effort modify it. can't in config file or in db etc.
so thinking about:
- hardcode them in case, what's elegant (least horrible) method? hardcode pair, triplet in namespace store in hash [enumvalue]->[struct]?
- store in file compiled resource file (although accessible tools, ask bit more effort user). checksum make sure wasn't modified if necessary guess?
what thoughts?
to summarize, have enum containing val1, val2 ...
and associate like:
val1 has length 5 , name "foo" val2 has length 8 , name "bar"
i might missing other easy solution though
this code adapted solution found while ago on stackoverflow post - if can find original link again i'll include give credit them.
i had similar problem wanted associate string
each enum value. adapting code case of pair of values this.
template<typename t> class enumparser { private: std::map<t, std::pair<int, std::string>> _map_enum_keyed; // map enum values keys public: enumparser(); // unspecified constructor t enum(const std::string &key) const; // enum value given string key std::pair<int, std::string> value(const t &key) const; // string value of given enum key }; // template definitions template<typename t> std::pair<int, std::string> enumparser<t>::value(const t &key) const { const auto &iterator = this->_map_enum_keyed.find(key); if(iterator == this->_map_enum_keyed.end()) { throw std::runtime_error("enumparser::value(const t &key) - error 1 - not find key"); } return iterator->second; }
you can use in cpp file associated header enum
declared specifying constructor enumparser initialised enum
template<>enumparser<your_enum>::enumparser() { this->_map_enum_keyed = { {your_enum::value1, std::make_pair(5, "foo")}, {your_enum::value2, std::make_pair(8, "bar")}, }; }
you can make more general adding second template parameter , replacing used std::pair
second template.
this particularly useful when wanting associate enum
std::string
can add in second map std::string
keys , template parameter values. reversing original map can turn string
enum
being able turn enum
string
Comments
Post a Comment