Created
November 25, 2022 21:21
-
-
Save kisasexypantera94/9e8a32ff99f864fb6dbf65496b35eec7 to your computer and use it in GitHub Desktop.
constexpr for loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <cassert> | |
| #include <iostream> | |
| #include <tuple> | |
| namespace details | |
| { | |
| template <size_t v> | |
| struct ConstexprNum | |
| { | |
| static constexpr auto value = v; | |
| constexpr operator size_t() { return v; } | |
| }; | |
| template <size_t i, size_t n, typename F> | |
| void ConstexprForIter(F func) | |
| { | |
| if constexpr (i < n) | |
| { | |
| func(ConstexprNum<i>{}); | |
| ConstexprForIter<i + 1, n, F>(func); | |
| } | |
| } | |
| template <size_t i, size_t n, typename F> | |
| void ConstexprForIter512(F func) | |
| { | |
| if constexpr (i < n) | |
| { | |
| ConstexprForIter<i, std::min(i + 512, n), F>(func); | |
| ConstexprForIter512<i + 512, n, F>(func); | |
| } | |
| } | |
| } // namespace details | |
| template <size_t n, typename F> | |
| void ConstexprFor(F func) | |
| { | |
| details::ConstexprForIter512<0, n, F>(func); | |
| } | |
| int main() | |
| { | |
| std::tuple t = std::make_tuple(0, 1, 2, 3, 4); | |
| constexpr auto t_size = std::tuple_size_v<decltype(t)>; | |
| ConstexprFor<t_size>([&](auto i) | |
| { | |
| std::cout << i << " " << std::get<i>(t) << std::endl; | |
| }); | |
| constexpr size_t big_i = 2048; | |
| size_t cnt = 0; | |
| ConstexprFor<big_i>([&](auto i) { cnt += i; }); | |
| assert(cnt == (big_i - 1) * big_i / 2); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment