Last active
November 14, 2017 16:10
-
-
Save paulgessinger/4700a9f893dfc2cc7ced530cdb1765c0 to your computer and use it in GitHub Desktop.
N Dimensional grid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <tuple> | |
namespace details { | |
template<class T>struct tag{using type=T;}; | |
template<class Tag>using type=typename Tag::type; | |
template<class T, size_t n> | |
struct n_dim_vec:tag< std::vector< type< n_dim_vec<T, n-1> > > > {}; | |
template<class T> | |
struct n_dim_vec<T, 0>:tag<T>{}; | |
template<class T, size_t n> | |
using n_dim_vec_t = type<n_dim_vec<T,n>>; | |
template <class T, class R=std::vector<T>> | |
R make_vector(size_t size) { | |
return R(size); | |
} | |
template<class T, class...Args, class R=n_dim_vec_t<T, sizeof...(Args)+1>> | |
R make_vector(size_t top, Args&&... args){ | |
return R(top, make_vector<T>(std::forward<Args>(args)...)); | |
} | |
} | |
template <class T, class... Args, class R=details::n_dim_vec_t<T, sizeof...(Args)>> | |
R make_vector(Args&&... args) | |
{ | |
return details::make_vector<T>(std::forward<Args>(args)...); | |
} | |
template <typename T> | |
T& get_vector(details::n_dim_vec_t<T, 1>& vec, size_t i) | |
{ | |
return vec.at(i); | |
} | |
template <typename T, | |
class... Indexes, | |
std::enable_if_t<sizeof...(Indexes) != 0, int> = 0> | |
T& get_vector(details::n_dim_vec_t<T, sizeof...(Indexes)+1>& vec, size_t i, Indexes&&... indexes) | |
{ | |
return get_vector<T>(vec.at(i), std::forward<Indexes>(indexes)...); | |
} | |
template<typename T, size_t D> | |
class Grid { | |
public: | |
template<class ...Args> | |
Grid(T def, Args... args) : m_data(details::make_vector<T>(std::forward<Args>(args)...)) {} | |
template<class... Indexes, std::enable_if_t<sizeof...(Indexes) == D, int> = 0> | |
T& operator()(Indexes&&... indexes) | |
{ | |
return get_vector<T>(m_data, std::forward<Indexes>(indexes)...); | |
} | |
private: | |
details::n_dim_vec_t<T, D> m_data; | |
}; | |
int main() { | |
Grid<double, 1> g(1, 5); | |
g(3) = 42; | |
Grid<double, 2> g2(1, 5, 5); | |
g2(1, 2) = 66; | |
g2(2, 1) = 79; | |
Grid<double, 3> g3(1, 5, 5, 6); | |
g3(1, 2, 3) = 66; | |
g3(2, 1, 3) = 79; | |
g3(3, 2, 1) = 37; | |
g3(3, 2, 5) = 99; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment