From 2bd1f7a94d4a43b61c059bca1fac295644bf6d4b Mon Sep 17 00:00:00 2001 From: Titus Winters Date: Tue, 17 Nov 2015 17:54:57 -0500 Subject: [PATCH] Fix the "enum class" example (which was backwards and broken). --- CppCoreGuidelines.md | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 7ccb8a2..4b44b34 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -6284,27 +6284,35 @@ An enumeration shows the enumerators to be related and can be a named type ##### Reason -To minimize surprises. +To minimize surprises: traditional enums convert to int too readily. ##### Example - enum Webcolor { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF }; - enum Productinfo { red=0, purple=1, blue=2 }; + void PrintColor(int color); + + enum Webcolor { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF }; + enum Productinfo { Red=0, Purple=1, Blue=2 }; - int webby = blue; // error, ambiguous: be specific Webcolor webby = Webcolor::blue; + // Clearly at least one of these calls is buggy. + PrintColor(webby); + PrintColor(Productinfo::Blue); + Instead use an `enum class`: - enum class Webcolor { red=0xFF0000, green=0x00FF00, blue=0x0000FF }; - enum class Productinfo { red=0, purple=1, blue=2 }; + void PrintColor(int color); + + enum class Webcolor { red=0xFF0000, green=0x00FF00, blue=0x0000FF }; + enum class Productinfo { Red=0, Purple=1, Blue=2 }; - int webby = blue; // error: blue undefined in this scope Webcolor webby = Webcolor::blue; + PrintColor(webby); // Error: cannot convert Webcolor to int. + PrintColor(Productinfo::Red); // Error: cannot convert Productinfo to int. ##### Enforcement -??? +(Simple) Warn on any non-class enum definition. ### Enum.4: Define operations on enumerations for safe and simple use