HiPipe  0.7.0
C++17 data pipeline with Python bindings.
for_each.hpp
1 /****************************************************************************
2  * hipipe library
3  * Copyright (c) 2017, Cognexa Solutions s.r.o.
4  * Copyright (c) 2018, Iterait a.s.
5  * Author(s) Filip Matzner
6  *
7  * This file is distributed under the MIT License.
8  * See the accompanying file LICENSE.txt for the complete license agreement.
9  ****************************************************************************/
10 
11 #pragma once
12 
13 #include <hipipe/core/stream/template_arguments.hpp>
14 #include <hipipe/core/stream/transform.hpp>
15 #include <hipipe/core/utility/tuple.hpp>
16 
17 namespace hipipe::stream {
18 
19 namespace detail {
20 
21  // Wrap the given function so that its return value is ignored
22  // and so that it can be forwarded to stream::transform.
23  template<typename Fun, typename... FromTypes>
24  struct wrap_void_fun_for_transform {
25  Fun fun;
26 
27  utility::maybe_tuple<FromTypes...> operator()(FromTypes&... args)
28  {
29  static_assert(std::is_invocable_v<Fun, FromTypes&...>,
30  "hipipe::stream::for_each: "
31  "Cannot apply the given function to the given `from<>` columns.");
32  std::invoke(fun, args...);
33  // we can force std::move here because the old
34  // data are going to be ignored anyway
35  return {std::move(args)...};
36  }
37  };
38 
39 } // namespace detail
40 
41 
61 template<typename... FromColumns, typename Fun, int Dim = 1>
62 auto for_each(from_t<FromColumns...> f, Fun fun, dim_t<Dim> d = dim_t<1>{})
63 {
64  static_assert(
65  ((utility::ndims<typename FromColumns::data_type>::value >= Dim) && ...),
66  "hipipe::stream::for_each: The dimension in which to apply the operation "
67  " needs to be at most the lowest dimension of all the from<> columns.");
68  // a bit of function type erasure to speed up compilation
69  using FunT = std::function<
70  void(utility::ndim_type_t<typename FromColumns::data_type, Dim>&...)>;
71  // wrap the function to be compatible with stream::transform
72  detail::wrap_void_fun_for_transform<
73  FunT, utility::ndim_type_t<typename FromColumns::data_type, Dim>...>
74  fun_wrapper{std::move(fun)};
75  // apply the dummy transformation
76  return stream::transform(f, to<FromColumns...>, std::move(fun_wrapper), d);
77 }
78 
79 } // namespace hipipe::stream
hipipe::stream::for_each
auto for_each(from_t< FromColumns... > f, Fun fun, dim_t< Dim > d=dim_t< 1 >{})
Apply a function to a subset of stream columns.
Definition: for_each.hpp:68
hipipe::stream::transform
auto transform(from_t< FromColumns... > f, to_t< ToColumns... > t, Fun fun, dim_t< Dim > d=dim_t< 1 >{})
Transform a subset of hipipe columns to a different subset of hipipe columns.
Definition: transform.hpp:218