what is an enum?

  • Thread starter Thread starter Peteroid
  • Start date Start date
P

Peteroid

Using VS C++.NET 2005 Express in clr:/pure syntax. I have this enum, defined
like so:

enum My_Enum
{
ENUM_0 = 0,
ENUM_1
} ;

My_Enum enum_var ;

I'm trying to save/load enum_var to/from a file using ostream/istream. But:

output << enum_var ; //ok
input >> enum_var ; //error

So I tried saving the 'int' value of the enum vaviable:

output << int(enum_var) ; // ok
input >> enum_var ; //error

and even this doesn't work:

output << int(enum_var) ; // ok

int value ;
input >> value ; // ok
enum_var = value ; // error, can't convert?!

Help!! : )

[==P==]
 
Peteroid said:
int value ;
input >> value ; // ok
enum_var = value ; // error, can't convert?!

int doesn't convert to an enum. You have to cast it:

int value;
input >> value;
enum_var = static_cast<My_Enum>(value);

Tom
 
Hi Tom,

Thanks for the workaround! : )

[==P==]

Tamas Demjen said:
int doesn't convert to an enum. You have to cast it:

int value;
input >> value;
enum_var = static_cast<My_Enum>(value);

Tom
 
int doesn't convert to an enum. You have to cast it:

Thanx for the workaraound, which I'm using! : )

However, how you explain this quote form an msdn2 on-line page:

http://msdn2.microsoft.com/en-us/library/17z041d4.aspx

The enum type
ANSI 3.5.2.2 The integer type chosen to represent the values of an
enumeration type
A variable declared as enum is an int.

So either they better take down this page or an enum variable IS an 'int',
let alone not being able to convert it to one! :)

[==P==]
 
Peter said:
Thanx for the workaraound, which I'm using! : )

It's not a workaround, that's the way of doing it.
However, how you explain this quote form an msdn2 on-line page:

http://msdn2.microsoft.com/en-us/library/17z041d4.aspx

The enum type
ANSI 3.5.2.2 The integer type chosen to represent the values of an
enumeration type
A variable declared as enum is an int.

An enum converts to an int, but an int doesn't convert to an enum
without at least a warning. Once you write your own operator>> for the
enum type, you can simply use that. It would be even better if enum
didn't convert to an int, then you couldn't mix things up accidentally.
I think if you're forced to do a cast, it's a kind of confirmation of
your intentions, telling the compiler that it's not an accident but
that's what you really want.

Tom
 
Back
Top