On 31.01.2012 23:56, Christopher wrote:
> A developer before me created a large enumeration we can call
> EnumType1.
> He then, right under it, typedef-ed another
>
> typedef EnumType1 EnumType2
>
> He then created a comment "alias, should only include x types", where
> x is a rule defining a subset of EnumType1
>
> This is crap imo. Any function or method declared to take EnumType2,
> would happily take a value from EnumType1 that does not meet the x
> criteria.
Exactly. You need different types.
> Since I know the subset from EmunType1 that meets the x criteria, how
> can I define a subset EnumType2 that only includes those enums without
> typing the whole darn subset twice?
There is no language support for this kind of problem.
AFAIK you have two options:
1. repeat the definition of the common constants.
2. declare your own enum classes.
In the latter case you need to know that Citrus is no subclass of Fruit,
because you can safely cast from the subset to the general one but not
the other way around.
class Citrus
{public:
static const Citrus ORANGE;
static const Citrus GRAPEFRUIT;
//...
protected:
Citrus() {}
};
class Fruit : Citrus
{ static const Fruit APPLE;
//...
protected:
Fruit() {}
};
bool operator==(const Citrus& l, const Citrus& r)
{ return &l == &r;
}
bool operator!=(const Citrus& l, const Citrus& r)
{ return &l != &r;
}
Note that this pseudo enums have no value, since the fixed number of
instances is already sufficient for uniqueness. This is similar to Java
2 like enums.
Things get complicated when you need to define different subsets.
Especially the comparison operators have to be overloaded appropriately.
And if you also require an associated int value, you need a virtual base
class holding that value or alternatively build your own lookup table to
ensure uniqueness over the related class types.
Marcel