Simplify a longer unrolled loop expression with constexpr or template metaprogramming

Viewed 200

It looks like I have a longer expression (unrolled loop) such as the code below several times in a piece of software which bloats it up by several thousand lines.

Since poly takes template arguments for performance (the second argument corresponds to the loops z value), I wonder whether one can simplify the code below by template meta programming and building by recursion something like a loop. The syntax of the expression seems to be for each x = bx (a + b + c * by * bz) + ..

I guess, it would be easier if poly wouldn't be a template function, but taking function parameters.

void calc(float mat[3][3][3], float fS, float fT, float fU)
{
    const float bs20_u = poly<2, 0>(fU);
    const float bs21_u = poly<2, 1>(fU);
    const float bs22_u = poly<2, 2>(fU);

    const float bs20_s = poly<2, 0>(fS);
    const float bs21_s = poly<2, 1>(fS);
    const float bs22_s = poly<2, 2>(fS);

    const float bs20_t = poly<2, 0>(fT);
    const float bs21_t = poly<2, 1>(fT);
    const float bs22_t = poly<2, 2>(fT);

    float result = 
       ((mat[0][0][0] * bs20_u + mat[0][0][1] * bs21_u + mat[0][0][2] * bs22_u) * bs20_t
      + (mat[0][1][0] * bs20_u + mat[0][1][1] * bs21_u + mat[0][1][2] * bs22_u) * bs21_t
      + (mat[0][2][0] * bs20_u + mat[0][2][1] * bs21_u + mat[0][2][2] * bs22_u) * bs22_t)
      * bs20_s
      +
       ((mat[1][0][0] * bs20_u + mat[1][0][1] * bs21_u + mat[1][0][2] * bs22_u) * bs20_t
      + (mat[1][1][0] * bs20_u + mat[1][1][1] * bs21_u + mat[1][1][2] * bs22_u) * bs21_t
      + (mat[1][2][0] * bs20_u + mat[1][2][1] * bs21_u + mat[1][2][2] * bs22_u) * bs22_t)
      * bs21_s
      +
       ((mat[2][0][0] * bs20_u + mat[2][0][1] * bs21_u + mat[2][0][2] * bs22_u) * bs20_t
      + (mat[2][1][0] * bs20_u + mat[2][1][1] * bs21_u + mat[2][1][2] * bs22_u) * bs21_t
      + (mat[2][2][0] * bs20_u + mat[2][2][1] * bs21_u + mat[2][2][2] * bs22_u) * bs22_t)
      * bs22_s;
}
1 Answers
Related