E 'questo quello che vuoi? L'inizializzazione è semplice e non è necessaria alcuna istanziazione.
utilizzo:
enum SomeEnum
{
ENUM_ONE,
ENUM_TWO,
ENUM_THREE,
ENUM_NULL
};
DEFINE_PAIRLIST(CEnumMap, SomeEnum)
INIT_PAIRLIST(CEnumMap)=
{
{"One", ENUM_ONE},
{"Two", ENUM_TWO},
{"Three", ENUM_THREE},
{"", ENUM_NULL}
};
main{
// Get enum from string
SomeEnum i = CEnumMap::findValue("One");
// Get string from enum
SomeEnum eee = ENUM_ONE;
const char* pstr = CEnumMap::findKey(eee);
...
}
libreria:
template <class T>
struct CStringPair
{
const char* _name;
T _value;
};
template <class T, class Derived>
struct CStringPairHandle
{
typedef CStringPair<T> CPair;
static const CStringPair<T> * getPairList(){
return Derived::implementation();
}
static T findValue(const char* name){
const CStringPair<T> * p = getPairList();
for (; p->_name[0]!=0; p++)
if (strcmp(name,p->_name)==0)
break;
return p->_value;
}
static const char* findKey(T value){
const CStringPair<T> * p = getPairList();
for (; p->_name[0]!=0; p++)
if (strcmp(value,p->_value)==0)
break;
return p->_name;
};
};
#define DEFINE_PAIRLIST(name, type) struct name:public CStringPairHandle<type, name>{ \
static CPair _pairList[]; \
static CPair* implementation(){ \
return _pairList; \
}};
#define INIT_PAIRLIST(name) name::CPair name::_pairList[]
fonte
2011-03-28 21:40:58
Perché non utilizzare un hasmap? Renderebbe la ricerca più efficiente? Beh, deve provare e misurare l'efficacia in quanto può dipendere dal numero di elementi nel tuo enum ... Con enum grande, hasmap potrebbe renderlo un modo più veloce per ottenere il valore, non è vero? –
hash_map non fa parte dello standard (e unordered_map è stato aggiunto solo in TR1). Inoltre, è probabile che ci sia una minima differenza tra hash_map e map a meno che non si inizi ad avere un numero molto elevato di valori enum.In ogni caso, è un passaggio facile da fare se la profilatura indica che qualcosa è troppo lento. La mappa di hash – Eclipse
sarebbe molto inefficiente per la maggior parte delle enumerazioni che hanno un numero molto limitato di valori. In effetti, la ricerca lineare può essere più efficiente di una mappa hash se l'enumerazione riguarda solo i normali 8 valori. Se ha 2 o 3, la ricerca lineare probabilmente batterà anche std :: map. – CashCow