|
Re: Typesafe Enums in C++
|
Posted: Jun 21, 2005 8:08 AM
|
|
> Another way to get some of the same benefits is a > "range-checking" template class. The enum constants are > still integers, but the variables you create are of a > template class that checks the values coming into the > initialization-constructor, copy-constructor, and > assignment operators, and coming out of the type-cast > operator. > > If a bad value is passed in, or the variable is somehow > changed without going through a constructor or assignment > operator, you can be notified through an assertion or > exception. > > enum FooType { fee, fi, fo, fum, foo }; > > CheckedEnum< FooType, fee, foo > aCheckedFooEnumVar; > > aCheckedFooEnumVar = (FooType) 12; // assertion or > exception thrown > > I leave the template class code to the reader.
This is a good idea, and I actually have a class which could be used in such a way, which I just posted to my blog at http://www.artima.com/weblogs/viewpost.jsp?thread=115788
It is policy based so the behaviour (e.g. assertion or exception) can be defined by the user.
|
|