tlx
Loading...
Searching...
No Matches
vmap_foreach_with_index.hpp
Go to the documentation of this file.
1/*******************************************************************************
2 * tlx/meta/vmap_foreach_with_index.hpp
3 *
4 * Part of tlx - http://panthema.net/tlx
5 *
6 * Copyright (C) 2016-2017 Timo Bingmann <tb@panthema.net>
7 *
8 * All rights reserved. Published under the Boost Software License, Version 1.0
9 ******************************************************************************/
10
11#ifndef TLX_META_VMAP_FOREACH_WITH_INDEX_HEADER
12#define TLX_META_VMAP_FOREACH_WITH_INDEX_HEADER
13
14#include <tuple>
15#include <utility>
16
18
19namespace tlx {
20
21//! \addtogroup tlx_meta
22//! \{
23
24/******************************************************************************/
25// Variadic Template Expander: run a generic templated functor (like a generic
26// lambda) for each of the variadic template parameters, and collect the return
27// values in a generic std::tuple.
28//
29// Called with func(StaticIndex<> index, Argument arg).
30
31namespace meta_detail {
32
33//! helper for vmap_foreach_with_index: base case
34template <size_t Index, typename Functor, typename Arg>
35auto vmap_foreach_with_index_impl(Functor&& f, Arg&& arg) {
36 return std::make_tuple(
37 std::forward<Functor>(f)(StaticIndex<Index>(), std::forward<Arg>(arg)));
38}
39
40//! helper for vmap_foreach_with_index: general recursive case
41template <size_t Index, typename Functor, typename Arg, typename... MoreArgs>
42auto vmap_foreach_with_index_impl(Functor&& f, Arg&& arg, MoreArgs&& ... rest) {
43 auto x =
44 std::forward<Functor>(f)(StaticIndex<Index>(), std::forward<Arg>(arg));
45 return std::tuple_cat(
46 std::make_tuple(std::move(x)),
47 vmap_foreach_with_index_impl<Index + 1>(
48 std::forward<Functor>(f), std::forward<MoreArgs>(rest) ...));
49}
50
51} // namespace meta_detail
52
53//! Call a generic functor (like a generic lambda) for each variadic template
54//! argument together with its zero-based index.
55template <typename Functor, typename... Args>
56auto vmap_foreach_with_index(Functor&& f, Args&& ... args) {
57 return meta_detail::vmap_foreach_with_index_impl<0>(
58 std::forward<Functor>(f), std::forward<Args>(args) ...);
59}
60
61//! \}
62
63} // namespace tlx
64
65#endif // !TLX_META_VMAP_FOREACH_WITH_INDEX_HEADER
66
67/******************************************************************************/
auto vmap_foreach_with_index(Functor &&f, Args &&... args)
Call a generic functor (like a generic lambda) for each variadic template argument together with its ...
auto vmap_foreach_with_index_impl(Functor &&f, Arg &&arg)
helper for vmap_foreach_with_index: base case
Helper for call_foreach_with_index() to save the index as a compile-time index.