我想为每个习语实现遍历2d / 3d矩阵的所有像素/体素。根据尺寸,我们有2个循环或3个循环。代码似乎是这样的:
//template class for point
template<int Dim>
struct Point{
int _data[Dim];
int & operator ()( int index){return _data[index];}
}
//template class for multi dimensional array
template<int Dim>
struct MatN{
enum{DIM=Dim};
Point<Dim> _domain;
std::vector<double> _data;
double & operator ()( Point<Dim> p){//in the real implementation template specialization
if(Dim==2)return _data[p(0)+p(1)*_domain(0)];
else if(Dim==3)return _data[p(0)+p(1)*_domain(0)+p(2)*_domain(0)*_domain(1)];
}
int sizeI(){return _domain(0);}
int sizeJ(){return _domain(1);}
int sizeK(){return _domain(2);}
};
#define ForEach(point,mat) ForEach##mat.DIM (point,mat) //compile error
#define ForEach2(point,mat)
Point<2> point;\
for(point(0)=0;point(0)<mat.sizeI();point(0)++)\
for(point(1)=0;point(1)<mat.sizeJ();point(1)++)
#define ForEach3(point,mat) \
Point<3> point;\
for(point(0)=0;point(0)<mat.sizeI();point(0)++)\
for(point(1)=0;point(1)<mat.sizeJ();point(1)++)\
for(point(2)=0;point(2)<mat.sizeK();point(2)++)
int main(){
MatN<2> m2d;
ForEach(p2,m2d){
//do something (in this process, I need the pixel position for a local process so I cannot use iterator)
//for instance
if(p2(0)*p2(1)>100)
m2d(p2)=1;
else
m2d(p2)=0;
}
MatN<3> m3d;
ForEach(p3,m3d){
//do something
}
}
问题是如何评估宏中的模板参数。
注意:出于依赖性原因,我不想使用boost。