Click here to Skip to main content
15,899,754 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have an enumerated type such as

enum Colors(Red, Blue, Green);

and a CString test_string = "Blue"

How do I get to the 2nd value in the enumerated type by the string?

What I am trying to get to is:

int retValue = Colors(test_string);

or something like that that will produce retValue = 1

I do not want to use if statements or case statements to accomplish this since I have about 100 elements in the enumeration. I would also like to keep this a simple as possible (I am not a great C programmer).
Posted

With C++ you have to do some work (C#, for instance gently provides it).
Your best bet is (unfortunately, maybe...) a std::map.
C++
// the enum
enum Color
{
  Red,
  Green,
  Blue
};

// the mapping of the string with the enum
map<CString , Color> m;
m.insert(make_pair<CString, Color>(_T("Red"),Red));
m.insert(make_pair<CString, Color>(_T("Green"),Green));
m.insert(make_pair<CString, Color>(_T("Blue"),Blue));

// usage...
Color c = m[_T("Green")];

 
Share this answer
 
There is no way to access the enum value by a string at runtime, like you want.

Put all possible srings in an array corresponding to your enumeration and use a loop to iterate through the array to find the int value for your string.
 
Share this answer
 
This usage could be thinkable too:
Colored<CString, Blue> cszString(_T("Blue"));
ASSERT(Blue == cszString.GetColor());

I describe it when you will want it... :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900