c++ - variadic multidimensional array -
could call multidimensional array like
func(0,0,0); //=> if know it's dimension on run time. func(0,0,0,0,0,0,0,0,0,0,0); //=> if know it's dimension on run time.
through of variadic templates
instead of:
data[0][0][0]; data[0][0][0][0][0][0][0][0][0][0][0];
this should work instead of doing data[1][2][3]
have use indexed(data,1,2,3)
it works plain arrays
std::arrays
. can extend std::vector
duplicating specializations. (i think should work thing overloads operator[] not sure.)
#include <iostream> #include <array> template<typename t, size_t dim> struct gettypeatdim { typedef t type; }; template<typename t, size_t n> struct gettypeatdim<t[n],1> { typedef t type; }; template<typename t, size_t dim, size_t n> struct gettypeatdim<t[n],dim> : gettypeatdim< t, dim-1> {}; template<typename t, size_t n> struct gettypeatdim<std::array<t,n>,1> { typedef t type; }; template<typename t, size_t dim, size_t n> struct gettypeatdim<std::array<t,n>,dim> : gettypeatdim< t, dim-1> {}; template<typename t, size_t dim> using typeatdim = typename gettypeatdim<t, dim>::type; template<typename t> typeatdim<t,1>& indexed(t& arr, const int& first) { return arr[first]; } template<typename t, typename... args> typeatdim<t,sizeof...(args) + 1>& indexed(t& arr, const int& first, const args& ...rest) { return indexed(arr[first],rest...); }
int main() { std::array<int,2> a1 = {1,2}; std::array<int,2> a2 = {3,4}; std::array<std::array<int,2>,2> = {a1,a2}; std::array<std::array<std::array<int,2>,2>,2> c = {a,a}; int b[2][2] = {{5,6},{7,8}}; std::cout << indexed(a,1,1) << std::endl; indexed(a,1,1) = 5; std::cout << indexed(a,1,1) << std::endl; std::cout << indexed(b,1,1) << std::endl; std::cout << indexed(c,1,1,1) << std::endl; indexed(c,1,1) = a1; std::cout << indexed(c,1,1,1) << std::endl; }
4 5 8 4 2
i not using auto
trailing return types
because the variadic version of indexed
not match when deducing type of return. until gets resolved gcc
have use this.
Comments
Post a Comment