Skip to content

Instantly share code, notes, and snippets.

@nekko1119
Created April 22, 2015 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nekko1119/3d5f5e4d1b7ee5c01681 to your computer and use it in GitHub Desktop.
Save nekko1119/3d5f5e4d1b7ee5c01681 to your computer and use it in GitHub Desktop.
#include <array>
#include <algorithm>
#include <iostream>
#include <tuple>
#include <utility>
template <typename ...Args, std::size_t N = sizeof...(Args)>
std::array<std::common_type_t<Args...>, N> make_array(Args&&... args)
{
return {{std::forward<Args>(args)...}};
}
template <std::size_t I, std::size_t N, typename ...Ts>
std::tuple<Ts...> unpack(std::array<Ts, N> const&... arr)
{
return std::make_tuple(arr[I]...);
}
template <typename ...Ts, std::size_t N, std::size_t ...Indices>
std::array<std::tuple<Ts...>, N> zip_impl(std::index_sequence<Indices...>, std::array<Ts, N> const&... arr)
{
return {{unpack<Indices>(arr...)...}};
}
template <typename ...Ts, std::size_t N>
std::array<std::tuple<Ts...>, N> zip(std::array<Ts, N> const&... arr)
{
return zip_impl(std::make_index_sequence<N>(), arr...);
}
template <typename ...Ts, std::size_t... N>
void disp(std::ostream& os, std::tuple<Ts...> const& t, std::index_sequence<N...>)
{
int unused[] = {0, (static_cast<void>(os << (N == 0 ? "" : ", ") << std::get<N>(t)), 0)...};
static_cast<void>(unused);
}
template <typename ...Ts>
std::ostream& operator<<(std::ostream& os, std::tuple<Ts...> const& t)
{
os << "(";
disp(os, t, std::make_index_sequence<sizeof...(Ts)>{});
return os << ")";
}
template <typename T, typename F, std::size_t N, std::size_t ...Indices>
void for_each_impl(std::array<T, N> const& arr, F&& f, std::index_sequence<Indices...>)
{
[](auto&&...){}((static_cast<void>(std::forward<F>(f)(arr[Indices])), 0)...);
}
template <typename T, std::size_t N, typename F>
void for_each(std::array<T, N> const& arr, F&& f)
{
for_each_impl(arr, std::forward<F>(f), std::make_index_sequence<N>{});
}
int main()
{
auto result = zip(make_array(1, 2, 3, 4, 5), make_array("a", "b", "c", "d", "e"));
std::for_each(result.begin(), result.end(), [](auto const& t) {
std::cout << t << std::endl;
});
auto arr = make_array(1.1, 2.2, 3.3, 4.4, 5.5);
for_each(arr, [](auto const& e) { std::cout << e << std::endl; });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment