I have the following code snippet:
enum { one } x;
enum { two } y;
x = y;
That will compile in C, but in C++, I get the following error:
test.c:6: error: cannot convert ‘main()::<anonymous enum>’ to ‘main()::<anonymous enum>’ in assignment
Can someone explain to me why this is happening? I would prefer an answer with some specifics about why the compiler behaves this way, rather than just “You can’t do that”
Converting from one enum type to another goes via an integer type (probably the underlying type of the source, not sure).
An implicit conversion from enum to an integer type is allowed in both C and C++. An implicit conversion from an integer type to enum is allowed in C, but not in C++.
Basically, C++ is being more type safe. It’s trying to stop you doing this:
If you want to perform this enum-enum conversion in C++, you could use typeof/declspec/boost typeof or equivalent. In GCC:
It doesn’t normally make sense to do so, though. For most purposes, enums (and especially anonymous ones) are “enumerated types”. They do just happen to be “implemented” by the C and C++ standards as integers wearing funny hats, but that doesn’t mean that
redis “equal to”hammerjust because they each appear first in two different enums (colours and tools respectively).static_castsuggests that there’s a relation between the two types involved. Any two enum types are “related” by the fact that both have an underlying integer type, and those are related, so the “relation” there really doesn’t say much. If you write this code you’re getting a pretty poor version of type safety.