diff --git a/lib/utility/doc/res/snippets/qx-helpers.cpp b/lib/utility/doc/res/snippets/qx-helpers.cpp new file mode 100644 index 00000000..beff8924 --- /dev/null +++ b/lib/utility/doc/res/snippets/qx-helpers.cpp @@ -0,0 +1,39 @@ +//! [0] +#include +#include +#include +#include +#include +#include + +// The variant to visit +using var_t = std::variant; + +int main() +{ + std::vector vec = {10, 15l, 1.5, true, 'c', "hello"}; + + std::function f = [](std::string arg) { std::cout << arg << " (from string std::function)"; }; + + for (auto& v : vec) + { + // Visit using aggregate + std::visit(qxFuncAggregate{ + [](auto arg) { std::cout << arg << " (from catch-all lambda) "; }, + [](double arg) { std::cout << std::fixed << arg << " (from double lambda) "; }, + [](bool arg) { std::cout << arg << " (from bool lambda) "; }, + [](char arg) { std::cout << arg << " (from char lambda) "; }, + f + }, v); + + std::cout << std::endl; + } +} + +// 10 (from catch-all lambda) +// 15 (from catch-all lambda) +// 1.500000 (from double lambda) +// 1 (from bool lambda) +// c (from char lambda) +// hello (from string std::function) +//! [0] \ No newline at end of file diff --git a/lib/utility/include/qx/utility/qx-helpers.h b/lib/utility/include/qx/utility/qx-helpers.h index ee7faf48..9d7311bf 100644 --- a/lib/utility/include/qx/utility/qx-helpers.h +++ b/lib/utility/include/qx/utility/qx-helpers.h @@ -4,6 +4,16 @@ // Standard Library Includes #include +//Non-namespace Structs---------------------------------------------------------- +/* TODO: Figure out how to constrain this to only accept functors, issue is at least as of C++20 + * there doesnt seem to be a way to check if a type has an arbitrary number of operator() overloads + * with an arbitrary number of arguments. + */ +template +struct qxFuncAggregate : Functors... { + using Functors::operator()...; +}; + //Non-namespace Functions---------------------------------------------------------- template const T qxAsConst(T&& t) { return std::move(t); } diff --git a/lib/utility/src/qx-helpers.dox b/lib/utility/src/qx-helpers.dox index 3f3bafb9..2ab839d5 100644 --- a/lib/utility/src/qx-helpers.dox +++ b/lib/utility/src/qx-helpers.dox @@ -6,6 +6,19 @@ * are designed to facilitate common fundamental tasks with as brief syntax as possible. */ +//Non-namespace Structs---------------------------------------------------------- +/*! + * @struct qxFuncAggregate + * + * A template struct that takes an arbitrary number of functors as arguments and, when + * instantiated, produces a struct with all `operator()` overloads from all provided functors. + * + * This helper struct is commonly used in the `std::variant` overload visit pattern to concisely + * implement a handler for all alternatives: + * + * @snippet qx-helpers.cpp 0 + */ + //Non-namespace Functions---------------------------------------------------------- /*! * @fn const T qxAsConst(T&& t) @@ -26,7 +39,6 @@ * qAsConst(). */ - /*! * @fn void qxDelete(T*& pointer) *