Casten von Enums
-
Ist es bei folgendem Code nötig explicit zu casten? Zumindest gibt es keine Meldungen vom Compiler (MSVC-9/10) hinsichtlich Typumwandlung, wenn ich nicht explizit caste.
#ifndef COLOR_H_ #define COLOR_H_ #include <assert.h> // assert() // Constants enum { COLOR_WHITE = 0, COLOR_BLACK = 1, COLOR_NONE = 2, }; // Inline functions inline int color_is_ok(int color) { return color == static_cast<int>(COLOR_WHITE) || color == static_cast<int>(COLOR_BLACK); // are these casts necessary? } inline int flip_color(int color) { assert(color_is_ok(color)); return static_cast<int>(color) ^ 1; // is this cast necessary? } #endif // COLOR_H_
-
Enum-Werte können implizit in int umgewandelt werden, die Casts sind also unnötig.
Der umgekehrte Weg hingegen bedarf einer expliziten Typumwandlung.
-
enums unterliegen der integral promotion, die Casts sind daher unnötig. Das heißt ein enum-element ist ok, wo ein int erwartet wird, aber ein int ist nicht ok, wenn ein Element des enums erwartet wird.
edit: zu langsam...
-
There is an implicit conversion from any enum type to int. But not vice versa.
Aber wenn du schon ein enum erstellst, wieso verwendest du diesen Typ dann nicht einfach als Parameter oder Rückgabewert?
Das abgeänderte Beispiel soll nur dazu dienen um dir zu zeigen was ich damit meine und sollte so vielleicht besser nicht übernommen werden.
#ifndef COLOR_H_ #define COLOR_H_ #include <assert.h> enum colors { COLOR_NONE, COLOR_WHITE, COLOR_BLACK }; inline bool color_is_ok(colors color) const { return color==COLOR_WHITE || color==COLOR_BLACK } inline colors flip_color(colors color) const { assert(color_is_ok(color)); if(color_is_ok(color)) return (color==COLOR_BLACK)?COLOR_WHITE:COLOR_BLACK else return COLOR_NONE; } #endif // COLOR_H_
-
Warum gibt es immer Leute, die den Enumeratoren Werte zuweisen, die sie ohnehin haben? Zumal die konkreten Zahlenwerte sowieso meistens nicht interessant sind...
Und ich würde in C++ den Header
<cassert>verwenden. Ansonsten schliesse ich mich enumerat0r an, abgesehen von dem folgenden Code, wo dasifneben demassertunnötig ist. Und so wie ich Tomahawk kenne, hat er Angst davor, dass der Compiler?:nicht wegoptimieren kann, und nimmt deshalb das massiv schnellere^.assert(color_is_ok(color)); if(color_is_ok(color)) return (color==COLOR_BLACK)?COLOR_WHITE:COLOR_BLACK else return COLOR_NONE;