What’s this failure: “error: invalid conversion from ‘int’ to

What’s this failure: “error: invalid conversion from ‘int’ to ‘number’ [-fpermissive]…“
And previously was defined:

int a=b=1;

enum number: int { k l m }

number = a+b;

Aren't both the same int type?
Last edited on
Please show us a complete example that reproduces the error message.

One of the purposes of enum classes is to have stronger-typed enums, so silenty casting it to int goes against its goals.
Use static_cast if you need to convert an enum class to its underlying type.
https://stackoverflow.com/a/8357366/8690169

Starting in C++14, an even better solution is to use the standard library's std::underlying_type_t
https://stackoverflow.com/a/33083231/8690169
Last edited on
no.
enum defines a type that is more or less a subset of integer. With strict compile rules, you cannot say enum = int. With looser compile flags, this is allowed by some compilers.


int = enum should work, and I do not think it will even warn you.

one way (there are many) to do int to enum is a switch..
enum e {a,b,c, defaulte};
int x = a;
...
e y = c;
switch(x) //all this to say y = x;
{
case a: y = a; break;
case b: y = b; break;
case c: y = c; break;
default: y = defaulte;
}

I havent tried the enum class. maybe it solves this issue cleaner?
you may also be able to force things with a cast if you are SURE that the int is a valid enum value. The switch and similar are for if you do not trust the int to be in range.

enum is very powerful and many, many tricks exist to do cool stuff with them. They are also at times rather limited.
Last edited on
Topic archived. No new replies allowed.