M
Mark A. Gibbs
i have been toying with the idea of making my enums smarter - ie, more
in line with the rest of the language. i haven't tested it yet, but what
i came up with is a template like this:
template <typename Enum>
class smart_enum
{
public:
typedef Enum enum_type;
smart_enum() {}
smart_enum(enum_type e) e_(e) {}
enum_type get() const { return e_; }
bool operator==(smart_enum const& e) const { return e.e_ == e_; }
bool operator!=(smart_enum const& e) const { return !(e_ == *this); }
operator enum_type() const { return e_; }
private:
enum_type e_;
};
i would like this to be used to transparently replace existing enum
types - with one exception. i want to disallow:
colour c = green;
and force:
colour c = colour::green;
otherwise, i want the template to behave exactly like a regular enum
type. would this template work? or am i missing anything?
the next thing i am thinking about is making the transition to smart
enums easy, using macros. something like this:
#define DEFINE_ENUM_START(enum_t) \
namespace enum_t ## _DUMB_ENUM_ { \
typedef enum
#define DEFINE_ENUM_END(enum_t) \
enum_t; } \
typedef smart_enum< enum_t ## _DUMB_ENUM_ :: enum_t > enum_t;
again, not tested or even compiled. but what i'd like to be able to do is:
DEFINE_ENUM_START(colour)
{
red,
green,
blue
}
DEFINE_ENUM_END(colour)
has anyone seen anything like this before? are there any problems with
doing this?
mark
in line with the rest of the language. i haven't tested it yet, but what
i came up with is a template like this:
template <typename Enum>
class smart_enum
{
public:
typedef Enum enum_type;
smart_enum() {}
smart_enum(enum_type e) e_(e) {}
enum_type get() const { return e_; }
bool operator==(smart_enum const& e) const { return e.e_ == e_; }
bool operator!=(smart_enum const& e) const { return !(e_ == *this); }
operator enum_type() const { return e_; }
private:
enum_type e_;
};
i would like this to be used to transparently replace existing enum
types - with one exception. i want to disallow:
colour c = green;
and force:
colour c = colour::green;
otherwise, i want the template to behave exactly like a regular enum
type. would this template work? or am i missing anything?
the next thing i am thinking about is making the transition to smart
enums easy, using macros. something like this:
#define DEFINE_ENUM_START(enum_t) \
namespace enum_t ## _DUMB_ENUM_ { \
typedef enum
#define DEFINE_ENUM_END(enum_t) \
enum_t; } \
typedef smart_enum< enum_t ## _DUMB_ENUM_ :: enum_t > enum_t;
again, not tested or even compiled. but what i'd like to be able to do is:
DEFINE_ENUM_START(colour)
{
red,
green,
blue
}
DEFINE_ENUM_END(colour)
has anyone seen anything like this before? are there any problems with
doing this?
mark