userver: userver/utils/constexpr_indices.hpp Source File
Loading...
Searching...
No Matches
constexpr_indices.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/constexpr_indices.hpp
4/// @brief Functions for iterating over a constexpr range of integers
5
6#include <cstddef>
7#include <type_traits>
8#include <utility>
9
10USERVER_NAMESPACE_BEGIN
11
12namespace utils {
13
14namespace impl {
15
16template <std::size_t... Indices, typename Func>
17void DoForEachIndex(std::index_sequence<Indices...>, Func func) {
18 static_assert(std::is_trivially_copyable_v<Func>);
19 (..., func(std::integral_constant<std::size_t, Indices>{}));
20}
21
22template <std::size_t... Indices, typename Func>
23void DoWithConstexprIndex(std::index_sequence<Indices...>,
24 std::size_t runtime_index, Func func) {
25 static_assert(std::is_trivially_copyable_v<Func>);
26 (..., (runtime_index == Indices
27 ? func(std::integral_constant<std::size_t, Indices>{})
28 : void()));
29}
30
31} // namespace impl
32
33/// Calls `func` with indices from range `0...<Count`, wrapped in
34/// `std::integral_constant`.
35template <std::size_t Count, typename Func>
36void ForEachIndex(Func func) {
37 impl::DoForEachIndex(std::make_index_sequence<Count>{}, func);
38}
39
40/// Calls `func` with `runtime_index` wrapped in `std::integral_constant`.
41template <std::size_t Count, typename Func>
42void WithConstexprIndex(std::size_t runtime_index, Func func) {
43 impl::DoWithConstexprIndex(std::make_index_sequence<Count>{}, runtime_index,
44 func);
45}
46
47} // namespace utils
48
49USERVER_NAMESPACE_END