【发布时间】:2017-07-11 14:11:35
【问题描述】:
看起来我有一个更长的表达式(展开循环),例如下面的代码在一个软件中多次膨胀了几千行。
由于poly 采用模板参数来提高性能(第二个参数对应于循环 z 值),我想知道是否可以通过模板元编程和递归构建来简化下面的代码,例如一个循环。表达式的语法似乎是每个x = bx (a + b + c * by * bz) + ..
我想,如果poly 不是模板函数,而是采用函数参数,那会更容易。
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;
}
【问题讨论】:
-
您可以从部分特化
poly开始,因为在您的情况下,它的第一个参数始终是2。 -
@iehrlich 但您不能部分特化函数模板...
-
我注意到如果可以专门化一个函数会更简单
-
@Quentin 但你可以写
template<int J> float poly2(float in) { return poly<2, J>(); } -
@iehrlich 超载了——足够接近 :)
标签: c++ c++11 templates template-meta-programming