wrapping enum in namespace ?
-
I'm maintaining old code. I can't use enum class. Do you wrap your enums in namespace to kinda simulate
enum class
? or is there a pattern Ì don't know about to make regular enum safer ? Thanks.CI/CD = Continuous Impediment/Continuous Despair
-
I'm maintaining old code. I can't use enum class. Do you wrap your enums in namespace to kinda simulate
enum class
? or is there a pattern Ì don't know about to make regular enum safer ? Thanks.CI/CD = Continuous Impediment/Continuous Despair
You don't need to go as far as a namespace, just a struct will do.
struct Color {
enum value { Red, Yello, Blue };
};int main()
{
Color::value box = Color::value::Red;
}If you want to be able to print Color::Red as a string, it's a bit more involved
#include
struct Color {
enum hue { Red, Yellow, Blue } value;
std::string as_string() {
std::string color;
switch(value) {
case Red : color = "Red"; break;
case Yellow : color = "Yellow"; break;
case Blue : color = "Blue"; break;
};
return color;
}
Color(Color::hue val) : value(val) {};
bool operator==(const Color&other) {
return value == other.value;
}
friend std::ostream& operator<<(std::ostream& os, const Color& color);
};std::ostream& operator<<(std::ostream& os, const Color& color)
{
os << color.value;
return os;
}int main()
{
Color x = Color::Red;
Color y = Color::Blue;
std::cout << x << '\n';
std::cout << x.as_string() << '\n';
if(x == y)
return 1;
else
return 0;
}"A little song, a little dance, a little seltzer down your pants" Chuckles the clown
-
You don't need to go as far as a namespace, just a struct will do.
struct Color {
enum value { Red, Yello, Blue };
};int main()
{
Color::value box = Color::value::Red;
}If you want to be able to print Color::Red as a string, it's a bit more involved
#include
struct Color {
enum hue { Red, Yellow, Blue } value;
std::string as_string() {
std::string color;
switch(value) {
case Red : color = "Red"; break;
case Yellow : color = "Yellow"; break;
case Blue : color = "Blue"; break;
};
return color;
}
Color(Color::hue val) : value(val) {};
bool operator==(const Color&other) {
return value == other.value;
}
friend std::ostream& operator<<(std::ostream& os, const Color& color);
};std::ostream& operator<<(std::ostream& os, const Color& color)
{
os << color.value;
return os;
}int main()
{
Color x = Color::Red;
Color y = Color::Blue;
std::cout << x << '\n';
std::cout << x.as_string() << '\n';
if(x == y)
return 1;
else
return 0;
}"A little song, a little dance, a little seltzer down your pants" Chuckles the clown
ahhhh yes, I've seen that before. thanks. :thumbsup:
CI/CD = Continuous Impediment/Continuous Despair