[glibmm/wip/dboles/Binding-master: 1/2] Binding: Use std::optional instead of out-ref+bool



commit 53e52c385864314224eb3cc1fb77262051863ab0
Author: Daniel Boles <dboles src gmail com>
Date:   Sat Nov 9 15:17:32 2019 +0000

    Binding: Use std::optional instead of out-ref+bool
    
    The pattern of returning a boolean to indicate whether an output
    reference was set is messy and error-prone. C++17 adds std::optional,
    which exists precisely to indicate that a result is available or not.
    
    A detail: Whereas glibmm-2-62 sets the `to` value unconditionally, even
    if the user returned false, this stops doing that. This should not be a
    problem, since FALSE stops GBinding using that GValue anyway, so we were
    just wasting cycles setting the new value – which was probably the same!

 glib/src/binding.hg | 21 ++++++++++++++-------
 1 file changed, 14 insertions(+), 7 deletions(-)
---
diff --git a/glib/src/binding.hg b/glib/src/binding.hg
index 840b0b62..067468c3 100644
--- a/glib/src/binding.hg
+++ b/glib/src/binding.hg
@@ -19,6 +19,8 @@
 #include <glibmm/ustring.h>
 #include <glibmm/value.h>
 
+#include <optional>
+
 _DEFS(glibmm,glib)
 _PINCLUDE(glibmm/private/object_p.h)
 
@@ -119,13 +121,14 @@ public:
    *
    * For instance:
    * @code
-   *   bool on_transform_to(const Glib::ustring& from_string, int& to_int);
+   *   std::optional<int> on_transform_to(const Glib::ustring& from_string);
    * @endcode
    *
-   * @return <tt>true</tt> if the transformation was successful, and <tt>false</tt> otherwise.
+   * @return a value of type <tt>T_to</tt> if the transformation was successful,
+   * and an empty optional with no value (i.e. <tt>std::nullopt</tt>) otherwise.
    */
   template <typename T_from, typename T_to>
-  using SlotTypedTransform = sigc::slot<bool(const T_from&, T_to&>);
+  using SlotTypedTransform = sigc::slot<std::optional<T_to> (const T_from&)>;
 
   /** Creates a binding between @a source_property and @a target_property,
    * allowing you to set the transformation functions to be used by the binding.
@@ -413,14 +416,18 @@ private:
     {
       Glib::Value<T_from> from_glib_value;
       from_glib_value.init(from_value);
+
       Glib::Value<T_to> to_glib_value;
       to_glib_value.init(to_value);
-      T_to to = to_glib_value.get();
 
-      const bool result = typed_transform(from_glib_value.get(), to);
-      to_glib_value.set(to);
+      const auto to = typed_transform(from_glib_value.get());
+
+      if (!to.has_value())
+        return false;
+
+      to_glib_value.set(*to);
       g_value_copy(to_glib_value.gobj(), to_value);
-      return result;
+      return true;
     }
 
   private:


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]