00001 #ifndef __MATH_ARRAY_ARRAY_H__
00002 #define __MATH_ARRAY_ARRAY_H__
00003
00004 template<typename... Args> inline void pass(Args&&...) {}
00005
00006 template <typename T = double, int D = 1> class array {
00007
00008 public:
00009 array() {
00010 for(int a = 0; a < D; ++a) shape[a] = 0;
00011 size = 0;
00012 v = NULL;
00013 }
00014
00015 void alloc_sub(int& a, int s) {
00016 size *= s;
00017 shape[a--] = s;
00018 }
00019
00020 template<typename... S> void zeros(S... s) {
00021
00022 }
00023
00024 void alloc(int const * s) {
00025 size = 1;
00026 for(int a = 0; a < D; ++a) {
00027 size *= s[a];
00028 shape[a] = s[a];
00029 }
00030
00031 v = new T[size];
00032 }
00033 template<typename... S> void alloc(S... s) {
00034 if(sizeof...(S) != D) throw;
00035
00036 int a = D-1;
00037 size = 1;
00038 pass((alloc_sub(a,s),1)...);
00039
00040 v = new T[size];
00041 }
00042
00043 void at_sub(int* i, int& a, int s) {
00044 i[a--] = s;
00045 }
00046
00047 template<int... S> T& at() {
00048 if(sizeof...(S) != D) throw;
00049
00050 int i[D];
00051 int a = D-1;
00052
00053 pass((at_sub(i,a,S),1)...);
00054
00055 return at(i);
00056 }
00057
00058 T& at(int* i) {
00059 T* t = v;
00060 int r = size;
00061 for(int a = 0; a < D; ++a) {
00062 r /= shape[a];
00063 t += r * i[a];
00064 }
00065 return *t;
00066 }
00067
00068 void print_sub(char const* fmt, int* i, int lvl) {
00069 if(lvl == (D-1)) {
00070 for(int a = 0; a < shape[lvl]; ++a) {
00071 i[lvl] = a;
00072 printf(fmt, at(i));
00073 }
00074 } else {
00075 for(int a = 0; a < shape[lvl]; ++a) {
00076 i[lvl] = a;
00077 print_sub(fmt, i, lvl+1);
00078 printf("\n");
00079 }
00080 }
00081 }
00082
00083
00084 array<T,D>& operator=(array<T,D> const & rhs) {
00085 alloc(rhs.shape);
00086 for(int a = 0; a < size; ++a) v[a] = rhs.v[a];
00087 return *this;
00088 }
00089 array<T,D>& operator+=(array<T,D> const & rhs) {
00090 if(size != rhs.size) {
00091 printf("operator+= size mismatch\n");
00092 throw;
00093 }
00094
00095 for(int a = 0; a < size; ++a) v[a] += rhs.v[a];
00096 return *this;
00097 }
00098 array<T,D>& operator+=(T const & rhs) {
00099 for(int a = 0; a < size; ++a) v[a] += rhs;
00100 return *this;
00101 }
00102
00103 array<T,D> operator+(array<T,D> const & rhs) {
00104 if(size != rhs.size) {
00105 printf("operator+ size mismatch\n");
00106 throw;
00107 }
00108
00109 array<T,D> r;
00110 r = *this;
00111 r += rhs;
00112 return r;
00113 }
00114 array<T,D> operator+(T const & rhs) {
00115 array<T,D> r = *this;
00116 r += rhs;
00117 return r;
00118
00119 }
00120
00121
00122
00123
00124 void print(char const* fmt) {
00125 int i[D];
00126 print_sub(fmt, i, 0);
00127 }
00128
00129
00130
00131 int shape[D];
00132 int size;
00133 T* v;
00134 };
00135
00136 #endif
00137