What I want to do is something similar to an enum. I want to declare a type that can only take on the integer values from 0 to 4, inclusive. I cannot seem to find a way to do this.
What I want to do is something similar to an enum. I want to declare a type that can only take on the integer values from 0 to 4, inclusive. I cannot seem to find a way to do this.
What's wrong with an enum?
I want to be able to use the actual integers, rather than an enumerated name.
Because he doesn't want an enum, which restrict what you can assign to a variable to a number of identifiers, but something that can be assigned to at will, just not anything other that 0 to 4. Basically, run-time bounds checking.
OP will have to find/implement a class that wraps up a normal integer and overloads the '=' operator to catch invalid values. Or switch to Pascal, Modula-9007, Ada, or any other of their ilk.
And it's not like an enum is any safeguard anyway:
Code:#include <stdio.h> int main() { enum enum_t {foo, bar, baz, quux} ; enum_t x; x = foo; // an error x = 1; // not an error x = (enum_t)7; return 0; }
The assignment "x = 1" in zx-1's example is not an error, but it does trigger a warning from most good quality compilers. Such warnings are eliminated by forcing the issue with an explicit conversion (and that, unfortunately, also allows assignment of invalid integral values to the enum).
Hmm, I will keep that in mind. I was actually going to implement this system into a class anyhow, and include the "enum" in a declarations header file. Overloading the = operator makes sense though.
You can use enum constructors to cast integers to enums and not generate any compiler warnings:
Code:enum Weekday { Mon = 0, Tues = 1, Wed = 2, Thurs = 3, Fri = 4 } Weekday day = Mon; day = Weekday( 2 ); // Now day == Wed. day = Weekday( 5 ); // Now day == 5 which isn't part of the enum (Sat maybe?) day = Weekday( Tues | Wed ); // Now day == 3 == Thurs.
You would probably also provide a (non-explicit) constructor that takes an int argument.Overloading the = operator makes sense though.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
It is where I'm sitting, at least:
It's not an error in C. Maybe that's what you're thinking of.Code:$ c++ try.cc try.cc: In function `int main()': try.cc:9: error: invalid conversion from `int' to `main()::enum_t'
===============================
So I see I left <stdio.h> in my example. That's a vestige of a previous try.c. So I guess it's not all your fault.
Last edited by zx-1; 01-01-2008 at 11:20 PM.