 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
edA-qa mort-ora-y Guest
|
Posted: Fri Jul 02, 2004 5:30 am Post subject: Strongly typed enums / enum iterators |
|
|
I've recently been using several enums for the purpose of loading/saving
data. What I've noticed would be quite helpful is a strongly typed
enum. I am sure this idea has been brought forward before, but I will
just add my viewpoint to it.
Basically given an enum:
enum Mode { One, Two, Three };
The old style of "just like an integer" can be kept for compatibility
and new operators introduced, or perhaps (as mentioned in the typedef
thread) use of an explicit keyword:
explicit enum Mode { One, Two, Three };
The "explicit" enum would then only allow assignment to/from an enum of
the same type. This of course requires a convesion operator, the
typical C cast could be used, but it might be cleaner to use a case like
syntax:
enum_cast<Mode>( 2 );
This would throw a "bad_cast" or "bad_enum" exception should the value
not be valid within the enum. Or perhaps have an option to assign a
default (but that might be too high-level logic for the standard).
-- --
The other aspect of this, which Java 1.5 seems to have added to their
new enums, is the ability to iterate over the enum values/names. For
this I propose that there is a template called enum_map, which is an STL
map of the name/values of the enum. Allowing something like this:
typedef enum_map<Mode> ModeMap;
for( ModeMap::iterator iter = ModeMap.begin();
iter != ModeMap.end(); iter++ )
cout << iter->first << "=" << iter->second << endl;
Where enum_map is a map of type map
underlying type required for the enum.
An alternate, which wouldn't require this weird singelton/statis class
would be:
enum_map modeMap( Mode );
A fixed class enum_map that takes the Enum as a constructore.
--
edA-qa mort-ora-y (Producer)
Trostlos Records <http://trostlos.org/>
"What suffering would man know if not for his own?"
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|