Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.milw.wisc.edu!lll-winken!uunet!mcvax!ukc!axion!stc!concurrent!asc From: asc@concurrent.co.uk (Andy Chittenden) Newsgroups: comp.lang.c++ Subject: Enumerated types in C++ Message-ID: <874@sl10c.concurrent.co.uk> Date: 14 Apr 89 06:22:47 GMT Reply-To: Andy Chittenden Organization: Concurrent Computer Corp (ESDG), Slough, U.K. Lines: 80 Enumerated types in C++ are not strictly typed like they are in other languages. A statement of the form: enum { FALSE = (0 != 0), TRUE = (0 == 0) } bool; does not prevent values other than TRUE or FALSE to be assigned to the variable bool. In C++, the above statement is synonymous with: declaring an int called bool declaring two constants called FALSE and TRUE. What this means is that strict type checking is not performed for enumerated types so if we have another enumerated type: enum { RED, BLUE, GREEN } colour; we are still allowed to say: colour = TRUE; Solution ________ The above problem can be circumvented by using two C++ classes for each enumerated type required. For example, class ColourEnumerator { enum { red, blue, green } colour; public: void RED(); void BLUE(); void GREEN(); }; void ColourEnumerator::RED() { colour = red; }; ..... and similarly for BLUE() and GREEN() typedef void (ColourEnumerator::*ColourEnumeratorMemberPtr)(); // it would be nice if this typedef could be // declared within the Colour class (although // Cfront doesn't object, the generated C does // not compile) class Colour { ColourEnumerator colour; public: Colour(); Colour& operator=(const Colour&); Colour& operator=(ColourEnumeratorMemberPtr); // I would like to make this a const // parameter also but C++ won't let me (any // ideas?) }; Colour::Colour() {} Colour& Colour::operator=(const Colour& p_colour) { colour = p_colour.colour; return *this; } Colour& Colour::operator=(ColourEnumeratorMemberPtr& p_setting) { (colour.*p_setting)(); // actually set the colour return *this; } Although the above looks complicated to set up, it enables very strong type checking when actually using a Colour. To set a Colour use: Colour x; x = ColourEnumerator::RED; // turns x RED Rgds, Andy Chittenden Concurrent Computer Corporation 227 Bath Road Slough SL1 4AX England