I've used Enum.GetValues
and Enum.GetName
in my C# project and would like to know if there were somekind of alternative in the standard C++ library?
Asked
Active
Viewed 282 times
1

orlp
- 112,504
- 36
- 218
- 315

Stackie Overflower
- 201
- 1
- 6
- 14
-
3Off-topic: This is a terrible question title. It suggests that you want to express a complete C# application as a C++ enum... which is clearly nonsense. Please choose a more precise and meaningful title. – stakx - no longer contributing Jul 19 '12 at 19:16
3 Answers
1
There's no easy way to do this. There are a few SO questions on the subject (not exactly this question, though):
-
Although the question is slightly different, the top solution in "Is there a simple script to convert C++ enum to string?" is also a great solution to this question. You use GCCXML to generate an XML description from your enum at build time, then run a build-time script that reads it and generates C++ code that initializes an array of values and a std::map from values to names. – Chiara Coetzee Jul 19 '12 at 19:14
1
You could roll your own with a class.
Widget.h:
#include <map>
#include <string>
using namespace std;
class Widget
{
public:
static Widget VALUE1, VALUE2, VALUE3;
type GetValue();
string GetName();
bool Widget::operator==(const Widget& other) const;
private:
// specific traits should be declared here
int i;
Widget(string name, int value);
static map<Widget, string> names;
}
Widget.cpp:
Widget::VALUE1 = Widget("VALUE1", 1);
// others
Widget::Widget(string name, int value)
{
i = value;
Widget::names[name] = *this; // this should happen after all initialization is done
}
bool Widget::operator==(const Widget& other) const
{
return (this->i == other.i);
}
Note: this probably isn't perfect. It's untested and very unlikely to magically work the first try.

Wug
- 12,956
- 4
- 34
- 54
0
I would use a stl::map if you need all the functionality of getting all the possible names and the associated int values.
In general, in c++ and using enums, you have to look at the documentation to get all the possible enum values or use namespaces or let the IDE tell you which ones are available when you are programming.
Sometimes, when writing enums, I'll prefix all the named values with some information that indicates what enum they belong to.

phyatt
- 18,472
- 5
- 61
- 80