Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Variadic expansion for aggregate initialization
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <utility>
#include <vector>
struct foo {
foo(int i) : data(i) {}
friend std::ostream& operator<<(std::ostream& os, foo const& f) {
return os << "foo(" << f.data << ")";
}
private:
int data;
};
template <typename Array, int... I>
Array iota_impl(std::integer_sequence<int, I...>) {
return {I...};
}
template <typename T, size_t N>
auto iota_array() {
using Sequence = std::make_integer_sequence<int, N>;
return iota_impl<std::array<T, N>>(Sequence{});
}
template <typename T, size_t N, size_t... I>
auto subarray_impl(std::array<T, N> const& arr,
size_t first,
std::index_sequence<I...>)
-> std::array<T, sizeof...(I)>
{
return {arr[first + I]...};
}
template <size_t S, typename T, size_t N>
auto subarray(std::array<T, N> const& arr, size_t first) {
using Indices = std::make_index_sequence<S>;
return subarray_impl(arr, first, Indices{});
}
template <typename Container, size_t... I>
std::ostream& print_impl(std::ostream& os, Container const& arr,
std::index_sequence<I...>)
{
// return (os << ... << arr[I]);
return ((os << arr[I] << ", "), ...);
}
template <typename T, size_t N>
std::ostream& operator<<(std::ostream& os, std::array<T, N> const& arr) {
using Indices = std::make_index_sequence<N>;
return print_impl(os, arr, Indices{});
}
int main () {
auto arr = iota_array<foo, 10>();
auto sub = subarray<4>(arr, 2);
std::cout << arr << std::endl;
std::cout << sub << std::endl;
}
@jgreitemann
Copy link
Author

jgreitemann commented Sep 15, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment