15 ms·
> In C [enumeration constants] are of type int, C++ they are of the enumeration type itself. > ... C and C++ have different rules for implicit conversion from
by quietbritishjim 6y ago
> In C [enumeration constants] are of type int, C++ they are of the enumeration type itself.
> ... C and C++ have different rules for implicit conversion from an to these types, so you better avoid using them [in function parameters]
Correct me if I misunderstood, but don't these differences cancel each other out? For example:
/* In header file */
enum Foo { FOO_A, FOO_B };
void bar(Foo f);
/* In code */
bar(FOO_A);
In C, FOO_A is an integer, but it's implicitly convertable to Foo so the call to bar is fine. In C++, int cannot implicitly convert to type Foo, but FOO_A is already of type Foo to begin with, so the function call is still fine. (In fact the call to bar() would in a .c or .cpp file so is allowed to be different between the two languages anyway.)
Edit: Another oddity in the article: If you want a function to work with a small number of different types, you would surely use simple function overloading rather than function template specialisation. In general it's a mistake to use function template specialisation, and there's certainly no need to use it here.
- goodcanadian 6y agoI believe: enum Foo { FOO_A, FOO_B }; is implicitly convertible to int even in C++. enum class Foo { FOO_A, FOO_B }; is not implicitly convertible, but can still be converted using static_cast.
- deleted 6y ago[deleted]
- quietbritishjim 6y agoIndeed, but I'm talking about the other way: int -> Foo. The article talked about "different rules for implicit conversion" so I assume they must have been referring to that direction.
- qalmakka 6y agoThis. Only `enum class` gives you a strongly-typed guarantee, `enum` can happily implicitly decay to `int` without any kind of warning. Lots of C libraries use `int` frequently together with enums without any sort of care, and it's too late to change this behaviour without creating an interoperability nightmare. The fact that `int` is not implicitly convertible to an enum type at least still saves you from a death from thousand cuts when a wrong value manages to get into an enum. The only sane way is to consider `enum` as a deprecated construct in C++ and use it as sparingly as possible, preferably only when interoperability with C makes them unavoidable.
- quietbritishjim 6y agoThis article is about code that will directly be compiled by both a C and C++ compiler, so indeed `enum class` is not an option here.