Skip to content

Instantly share code, notes, and snippets.

@nikhedonia
Last active October 24, 2015 19:16
Show Gist options
  • Save nikhedonia/8b76b06ef7d0c15ed9e7 to your computer and use it in GitHub Desktop.
Save nikhedonia/8b76b06ef7d0c15ed9e7 to your computer and use it in GitHub Desktop.
Opaque Functional MatrixType
#include <iostream>
using namespace std;
template<class Getter>
struct VectorF {
const size_t N;
Getter Get;
template<class T>
constexpr VectorF(size_t N, T Get)
: N(N),Get(Get)
{}
decltype(auto) operator[](size_t i){ return Get(i); }
auto const operator[](size_t i)const{ return Get(i); }
};
template<class F>
constexpr auto Vectorify(size_t N, F f){
return VectorF<F>(N,f);
}
template<class Getter>
struct MatrixF {
size_t M;
size_t N;
Getter Get;
template<class T>
MatrixF(size_t M, size_t N, T Get)
: M(M), N(N), Get(Get){}
auto operator[](size_t i)const{
return Vectorify(N, [this,i](size_t j)->auto&{ // yap, Views cannot outlive its parent...
return Get(i,j);
});
}
};
template<class F>
constexpr auto Vectorify(size_t M, size_t N, F f){
return MatrixF<F>(M,N,f);
}
int main() {
auto M=Vectorify(
2,2, // MxN matrix
[ data=(int[2][2]) {{1,2},{3,4}}]
(auto i, auto j) -> auto&{ // data is mutable
return data[i][j]; // access-pattern can be inlined
}
);
M[1][1]=5;
cout<< M[1][1];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment