我写了一个说明问题的小例子。 solve_bs1_y
和solve_bs2_y
实现完全相似。唯一的区别是函数调用:solve_bs*_z
。不幸的是,似乎不可能将模板作为参数传递来替换solve_bs*_z
的函数调用。因此,我必须为每个solve_bs*_z
另一个solve_bs*_y
实施。有没有办法简化代码,以便我只需要一个solve_bs_y
的实现?
// Example program
#include <iostream>
#include <string>
template <int x, int y, int offs, class T>
float solve_bs1_z(T mat, float fS, float fT, float fU) {
return 1; // to keep it simple
}
template <int x, int y, int offs, class T>
float solve_bs2_z(T mat, float fS, float fT, float fU) {
return 2; // to keep it simple
}
// essentially the same as solve_bs2_y
template <int x, int offs, class T>
float solve_bs1_y(T mat, float fS, float fT, float fU) {
const float bs_s = 2;
return ( solve_bs1_z<x, 0, offs>(mat, fS, fT, fU)
+ solve_bs1_z<x, 1, offs>(mat, fS, fT, fU)
+ solve_bs1_z<x, 2, offs>(mat, fS, fT, fU))
* bs_s;
}
// essentially the same as solve_bs1_y
template <int x, int offs, class T>
float solve_bs2_y(T mat, float fS, float fT, float fU) {
const float bs_s = 2;
return ( solve_bs2_z<x, 0, offs>(mat, fS, fT, fU)
+ solve_bs2_z<x, 1, offs>(mat, fS, fT, fU)
+ solve_bs2_z<x, 2, offs>(mat, fS, fT, fU) )
* bs_s;
}
// these are called in the program ..
template<int offs, class T>
float solve_ffd_bs1(T mat, float fS, float fT, float fU) {
return solve_bs1_y<0, offs>(mat, fS, fT, fU) +
solve_bs1_y<1, offs>(mat, fS, fT, fU) +
solve_bs1_y<2, offs>(mat, fS, fT, fU);
}
template<int offs, class T>
float solve_ffd_bs2(T mat, float fS, float fT, float fU) {
return solve_bs2_y<0, offs>(mat, fS, fT, fU) +
solve_bs2_y<1, offs>(mat, fS, fT, fU) +
solve_bs2_y<2, offs>(mat, fS, fT, fU);
}
int main()
{
int mat[3][3][3] = {
{{1,2,3}, {4,5,6}, {7,8,9}},
{{11,2,3}, {14,5,6}, {17,8,9}},
{{21,2,3}, {24,5,6}, {27,8,9}}
};
solve_ffd_bs2<0>(mat, 1,2,3);
return 0;
}
答案 0 :(得分:5)
没有结构模板的包装器版本:
struct s1 {
template <int x, int y, int offs, class T>
static float solve_bs_z(T mat, float fS, float fT, float fU) {
return 1; // to keep it simple
}
};
struct s2 {
template <int x, int y, int offs, class T>
static float solve_bs_z(T mat, float fS, float fT, float fU) {
return 2; // to keep it simple
}
};
template <class Wrapper, int x, int offs, class T>
float solve_bs_y(T mat, float fS, float fT, float fU) {
const float bs_s = 2;
return ( Wrapper::template solve_bs_z<x, 0, offs>(mat, fS, fT, fU)
+ Wrapper::template solve_bs_z<x, 1, offs>(mat, fS, fT, fU)
+ Wrapper::template solve_bs_z<x, 2, offs>(mat, fS, fT, fU))
* bs_s;
}
然后致电:
solve_bs_y<s1, 0, 1>(...);