Re: How to elegantly get the enum code from its string type
This is a MIME GnuPG-signed message. If you see this text, it means that
your E-mail or Usenet software does not support MIME signed messages.
The Internet standard for MIME PGP messages, RFC 2015, was published in 1996.
To open this message correctly you will need to install E-mail or Usenet
software that supports modern Internet standards.
--=_mimegpg-commodore.email-scan.com-23488-1271157043-0001
Content-Type: text/plain; format=flowed; charset="US-ASCII"
Content-Disposition: inline
Content-Transfer-Encoding: 7bit
thomas writes:
Hi guys,
I got a problem in practice, and I cannot find a verly elegant
solution to it.
------------------------------------------------------------------------
enum Type{
REPLY = 100,
REP = 1052,
HAHA = 9523,
};
------------------------------------------------------------------------
When I open the interface to users for configuration, I would like the
user to use "REPLY", "REP", "HAHA" like string format because it's
much easier to recognize and remember.
But in my program, I need to use the actual code (integral format).
My solution is to define a map<string, int>, and insert the string and
integral format pairs into the map for query. But it's really anoying
and difficult to use, especially when initializing.
Is there any elegant solution to this problem?
That's pretty much it. You can only play some preprocessor tricks, to save
some repetitive coding. Put something like this into a standalone header
file, enum_decl.h:
ENUM_DECL(REPLY,100)
ENUM_DECL(REP,1052)
ENUM_DECL(HAHA,9523)
Then, to declare your enum:
#define ENUM_DECL(name,value) name=value,
enum Type {
#include "enum_decl.h"
};
#undef ENUM_DECL
#define ENUM_Q(x) #x
#define ENUM_DECL(name,value) Type_map[ENUM_Q(name)]=name;
std::map<std::string, Type> Type_map;
void init()
{
#include "enum_decl.h"
}
#undef ENUM_DECL
The end result is that the enumeration is defined in enum_decl.h, indirectly
via the macro. Updating the list of enum values in enum_decl.h ends up
simultaneously updating the actual enum definition and the code that
initializes the map.
--=_mimegpg-commodore.email-scan.com-23488-1271157043-0001
Content-Type: application/pgp-signature
Content-Transfer-Encoding: 7bit
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.10 (GNU/Linux)
iEYEABECAAYFAkvEUTMACgkQx9p3GYHlUOLjjQCfSSw7anW3N9/LVtGMlJLb6e+c
IoAAnjC5YYGlDGNsTaX2zH4nCB2TYoRN
=SPFU
-----END PGP SIGNATURE-----
--=_mimegpg-commodore.email-scan.com-23488-1271157043-0001--