From 07c87d1d45af4a3c8111445ab6e6a7863b235d3a Mon Sep 17 00:00:00 2001 From: Stanislaw Halik Date: Thu, 4 May 2017 16:37:00 +0200 Subject: compat: add map/filter template functions --- compat/functional.hpp | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 compat/functional.hpp diff --git a/compat/functional.hpp b/compat/functional.hpp new file mode 100644 index 00000000..e7229d6e --- /dev/null +++ b/compat/functional.hpp @@ -0,0 +1,75 @@ +#pragma once + +#include +#include +#include + +namespace functools +{ + +constexpr void return_void(); + +template +using remove_qualifiers = std::remove_reference_t>; + +template +struct reserver_ +{ + static inline void maybe_reserve_space(seq_&, unsigned) + { + //qDebug() << "nada"; + } +}; + +template +struct reserver_().reserve(0u), return_void())> +{ + static inline void maybe_reserve_space(seq_& seq, unsigned sz) + { + seq.reserve(sz); + } +}; + +template +inline void maybe_reserve_space(seq_& seq, unsigned sz) +{ + reserver_::maybe_reserve_space(seq, sz); +} + +} // ns + +template +auto map(F&& fun, const seq_& seq) +{ + using seq_type = functools::remove_qualifiers; + + seq_type ret; + std::back_insert_iterator it = std::back_inserter(ret); + + for (const auto& elt : seq) + it = fun(elt); + + return ret; +} + +template +auto remove_if_not(F&& fun, const seq_& seq) +{ + using namespace functools; + + using seq_type = remove_qualifiers; + using value_type = typename std::iterator_traits()))>::value_type; + using fun_ret_type = decltype(fun(std::declval())); + static_assert(std::is_convertible::value, "must return bool"); + + seq_type ret; + maybe_reserve_space(ret, seq.size()); + + std::back_insert_iterator it = std::back_inserter(ret); + + for (const value_type& elt : seq) + if (fun(elt)) + it = elt; + + return ret; +} -- cgit v1.2.3