I have just started to use template meta-programming in my code. I have a class which has as a member which is a vector of a multi-dimensional Cartesian points. Here is a basic setup of the class:
template<size_t N>
class TGrid{
public:
void round_points_3(){
for(std::size_t i = 0; i < Xp.size();i++){
Xp[i][0] = min[0] + (std::floor((Xp[i][0] - min[0]) * nbins[0] / (max[0] - min[0])) * bin_w[0]) + bin_w[0]/2.0;
Xp[i][1] = min[1] + (std::floor((Xp[i][1] - min[1]) * nbins[1] / (max[1] - min[1])) * bin_w[1]) + bin_w[1]/2.0;
Xp[i][2] = min[2] + (std::floor((Xp[i][2] - min[2]) * nbins[2] / (max[2] - min[2])) * bin_w[2]) + bin_w[2]/2.0;
}
}
void round_points_2(){
for(std::size_t i = 0; i < Xp.size();i++){
Xp[i][0] = min[0] + (std::floor((Xp[i][0] - min[0]) * nbins[0] / (max[0] - min[0])) * bin_w[0]) + bin_w[0]/2.0;
Xp[i][1] = min[1] + (std::floor((Xp[i][1] - min[1]) * nbins[1] / (max[1] - min[1])) * bin_w[1]) + bin_w[1]/2.0;
}
}
void round_points_1(){
for(std::size_t i = 0; i < Xp.size();i++){
Xp[i][0] = min[0] + (std::floor((Xp[i][0] - min[0]) * nbins[0] / (max[0] - min[0])) * bin_w[0]) + bin_w[0]/2.0;
}
}
public:
std::vector<std::array<double,N> > Xp;
std::vector<double> min, max, nbins, bin_w;
};
This class represented a multidimensional Grid. The dimension is specified by the template value N. I will be having many operations which can be made more efficient by having template specific member functions tailored to the specific dimensions, such as loop unrolling.
In the class TGrid, I have 3 functions specific for dimensions D=1,D=2 and D=3. This is indicated by the subscript _1,_2 and _3 of the functions.
I am looking for a template meta-programming oriented approach to write these three functions more compactly.
I have seen examples of loop unrolling but all of these examples don't consider member functions of a template class.
round_pointsand a second loop.array::size()is constexpr and the compiler will then decide by itself if unrolling the loop is a good idea.