Suppose we have an enum like the following:
enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
I want to crea
If we want the strict type safety and scoped enum, using enum class is good in C++11.
If we had to work in C++98, we can using the advice given by InitializeSahib,San to enable the scoped enum.
If we also want the strict type safety, the follow code can implement somthing like enum.
#include
class Color
{
public:
static Color RED()
{
return Color(0);
}
static Color BLUE()
{
return Color(1);
}
bool operator==(const Color &rhs) const
{
return this->value == rhs.value;
}
bool operator!=(const Color &rhs) const
{
return !(*this == rhs);
}
private:
explicit Color(int value_) : value(value_) {}
int value;
};
int main()
{
Color color = Color::RED();
if (color == Color::RED())
{
std::cout << "red" << std::endl;
}
return 0;
}
The code is modified from the class Month example in book Effective C++ 3rd: Item 18