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...>, std::size_t runtime_index, Func func) {
24 static_assert(std::is_trivially_copyable_v<Func>);
25 (..., (runtime_index == Indices ? func(std::integral_constant<std::size_t, Indices>{}) : void()));
26}
27
28} // namespace impl
29
30/// Calls `func` with indices from range `0...<Count`, wrapped in
31/// `std::integral_constant`.
32template <std::size_t Count, typename Func>
33void ForEachIndex(Func func) {
34 impl::DoForEachIndex(std::make_index_sequence<Count>{}, func);
35}
36
37/// Calls `func` with `runtime_index` wrapped in `std::integral_constant`.
38template <std::size_t Count, typename Func>
39void WithConstexprIndex(std::size_t runtime_index, Func func) {
40 impl::DoWithConstexprIndex(std::make_index_sequence<Count>{}, runtime_index, func);
41}
42
43} // namespace utils
44
45USERVER_NAMESPACE_END