Skip to content

Commit

Permalink
lib/framework: add for_each_tuple utility function
Browse files Browse the repository at this point in the history
A simple compile-time utility to invoke a given function
over the elements of any tuple-like type (i.e. `std::tuple`,
`std::pair` and `std::array`).

Signed-off-by: Pavel Solodovnikov <[email protected]>
  • Loading branch information
ManManson committed Aug 10, 2024
1 parent 85310b6 commit 65f0cd6
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions lib/framework/for_each_tuple.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
This file is part of Warzone 2100.
Copyright (C) 2024 Warzone 2100 Project
Warzone 2100 is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Warzone 2100 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/** @file
* Utility function for iterating tuple-like types (std::tuple, std::array, std::pair).
*/
#pragma once

#include <tuple>
#include <utility>

namespace detail
{

template <typename TupleLike, typename Fn>
void for_each_tuple_impl(TupleLike&& tuple, Fn&& f, std::index_sequence<>)
{}

template <typename TupleLike, typename Fn, size_t CurrentIndex, size_t... RemainingIndices>
void for_each_tuple_impl(TupleLike&& tuple, Fn&& f, std::index_sequence<CurrentIndex, RemainingIndices...>)
{
f(std::get<CurrentIndex>(tuple));
for_each_tuple_impl(std::forward<TupleLike>(tuple), std::forward<Fn>(f), std::index_sequence<RemainingIndices...>{});
}

template <typename TupleLike, typename Fn, std::size_t NumElements, typename IndexSequence = std::make_index_sequence<NumElements>>
void for_each_tuple_helper(TupleLike&& tuple, Fn&& f)
{
for_each_tuple_impl(std::forward<TupleLike>(tuple), std::forward<Fn>(f), IndexSequence{});
}

} // namespace detail

template <typename TupleLike, typename Fn>
void for_each_tuple(TupleLike&& tuple, Fn&& f)
{
detail::for_each_tuple_helper<TupleLike, Fn, std::tuple_size<TupleLike>::value>(
std::forward<TupleLike>(tuple), std::forward<Fn>(f));
}

0 comments on commit 65f0cd6

Please sign in to comment.