Skip to content

Instantly share code, notes, and snippets.

@mtao
Created September 20, 2017 20:33
Show Gist options
  • Save mtao/e227427a62c88446775432deb2af073d to your computer and use it in GitHub Desktop.
Save mtao/e227427a62c88446775432deb2af073d to your computer and use it in GitHub Desktop.
a silly mechanism for experimenting with variadic templates. I'm hoping there's a way to do tihs without helper functions?
#include <array>
#include <iostream>
#include <utility>
#include <iterator>
template <int N, typename T, typename... Types>
struct NthPackTerm {
using type = typename NthPackTerm<N-1,Types...>::type;
};
template <typename T, typename... Types>
struct NthPackTerm<0,T,Types...> {
using type = T;
};
template <typename IdxType>
void _fillArray(IdxType& idx, std::index_sequence<>) {
}
template <typename IdxType, size_t I,size_t... Is, typename... Args>
inline void _fillArray(IdxType& idx, std::index_sequence<I,Is...>, typename IdxType::value_type v, Args... args) {
idx[I] = v;
_fillArray(idx,std::index_sequence<Is...>{}, args...);
}
template <typename... Args>
auto fillArray(Args... args) {
using value_type = typename NthPackTerm<0,Args...>::type;
std::array<value_type,sizeof...(args)> idx;
//why not see if this assert works with a fold expression
static_assert((std::is_same<value_type,Args>::value && ...));
_fillArray(idx,std::make_index_sequence<sizeof...(args)>{},args...);
return idx;
}
template <typename... Args>
auto fillArrayInitializerList(Args... args) {
using value_type = typename NthPackTerm<0,Args...>::type;
return std::array<value_type,sizeof...(args)>{args...};
}
int main(int argc, char * argv[]) {
auto a = fillArray(1,2,3,4,6);
std::copy(a.begin(),a.end(),std::ostream_iterator<decltype(a)::value_type>(std::cout,", "));
std::cout << std::endl;
//Just to show i'm ont an idiot and know this is valid
auto b = fillArrayInitializerList(1,2,3,4,6);
std::copy(b.begin(),b.end(),std::ostream_iterator<decltype(b)::value_type>(std::cout,", "));
std::cout << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment