funchelpers: Add a way to invoke a callable with a list of arguments
[quassel.git] / src / common / funchelpers.h
index c56cdb9..fcd5aa4 100644 (file)
 
 #pragma once
 
+#include <array>
 #include <functional>
 #include <tuple>
+#include <type_traits>
+#include <utility>
+
+#include <QDebug>
+#include <QVariantList>
+
+// ---- Function traits --------------------------------------------------------------------------------------------------------------------
 
 namespace detail {
 
@@ -62,3 +70,51 @@ struct FuncHelper<R(C::*)(Args...) const> : public FuncHelper<R(C::*)(Args...)>
  */
 template<typename Callable>
 using FunctionTraits = detail::FuncHelper<Callable>;
+
+// ---- Invoke function with argument list -------------------------------------------------------------------------------------------------
+
+namespace detail {
+
+// Helper for unpacking the argument list via an index sequence
+template<typename Callable, std::size_t ...Is, typename ArgsTuple = typename FunctionTraits<Callable>::ArgsTuple>
+bool invokeWithArgsList(const Callable& c, const QVariantList& args, std::index_sequence<Is...>)
+{
+    // Sanity check that all types can be converted
+    std::array<bool, std::tuple_size<ArgsTuple>::value> convertible{{args[Is].canConvert<std::decay_t<std::tuple_element_t<Is, ArgsTuple>>>()...}};
+    for (size_t i = 0; i < convertible.size(); ++i) {
+        if (!convertible[i]) {
+            qWarning() << "Cannot convert parameter" << i << "from type" << args[static_cast<int>(i)].typeName() << "to expected argument type";
+            return false;
+        }
+    }
+
+    // Invoke callable
+    c(args[Is].value<std::decay_t<std::tuple_element_t<Is, ArgsTuple>>>()...);
+    return true;
+}
+
+}  // detail
+
+/**
+ * Invokes the given callable with the arguments contained in the given variant list.
+ *
+ * The types contained in the given QVariantList are converted to the types expected by the callable.
+ * If the conversion fails, or if the argument count does not match, this function returns false and
+ * the callable is not invoked.
+ *
+ * @param c    Callable
+ * @param args Arguments to be given to the callable
+ * @returns true if the callable could be invoked with the given list of arguments
+ */
+template<typename Callable>
+bool invokeWithArgsList(const Callable& c, const QVariantList& args)
+{
+    using ArgsTuple = typename FunctionTraits<Callable>::ArgsTuple;
+    constexpr auto tupleSize = std::tuple_size<ArgsTuple>::value;
+
+    if (tupleSize != args.size()) {
+        qWarning().nospace() << "Argument count mismatch! Expected: " << tupleSize << ", actual: " << args.size();
+        return false;
+    }
+    return detail::invokeWithArgsList(c, args, std::make_index_sequence<tupleSize>{});
+}