Skip to content

Instantly share code, notes, and snippets.

@kisasexypantera94
Created November 25, 2022 21:21
Show Gist options
  • Select an option

  • Save kisasexypantera94/9e8a32ff99f864fb6dbf65496b35eec7 to your computer and use it in GitHub Desktop.

Select an option

Save kisasexypantera94/9e8a32ff99f864fb6dbf65496b35eec7 to your computer and use it in GitHub Desktop.
constexpr for loop
#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