quicknir/wise_enum

Compile for arduino (without exceptions support)

Closed this issue · 1 comments

I'm trying to use wise_enum for an arduino based project and got into trouble. The problem is that arduino doesn't have support for exceptions (compiled with -fno-exceptions). I did the following minor modification as exceptions were only used in optional.h to get it to work. However, my changes ignores the flag m_active and will return the old object even tough it's not valid any more. What's your thoughts ?

diff --git a/src/wise_enum/optional.h b/src/wise_enum/optional.h
index 7e07235..f05a0c3 100644
--- a/src/wise_enum/optional.h
+++ b/src/wise_enum/optional.h
@@ -37,31 +37,32 @@ public:

   constexpr explicit operator bool() const noexcept { return m_active; }
   constexpr bool has_value() const noexcept { return m_active; }
+  constexpr void try_throw() {
+#ifdef __EXCEPTIONS
+        throw bad_optional_access{};
+#endif
+  }

   WISE_ENUM_CONSTEXPR_14 T &value() & {
-    if (m_active)
-      return m_t;
-    else
-      throw bad_optional_access{};
+    if (!m_active)
+        try_throw();
+    return m_t;
   }
   constexpr const T &value() const & {
-    if (m_active)
-      return m_t;
-    else
-      throw bad_optional_access{};
+    if (!m_active)
+        try_throw();
+    return m_t;
   }

   WISE_ENUM_CONSTEXPR_14 T &&value() && {
-    if (m_active)
-      return m_t;
-    else
-      throw bad_optional_access{};
+    if (!m_active)
+        try_throw();
+    return m_t;
   }
   constexpr const T &&value() const && {
-    if (m_active)
-      return m_t;
-    else
-      throw bad_optional_access{};
+    if (!m_active)
+        try_throw();
+    return m_t;
   }

   template <class U>

@ramboerik Hey, sorry didn't respond directly here. I went with an approach more similar to standard library, where optional::value calls abort if the optional is empty. If you are building without exceptions then of course I would suggest always checking your optionals before dereferencing and probably just avoiding value completely :-) There's actually another issue open about no exception support, please give feedback there, cheers.