gpt4 book ai didi

c++ - 通过将模板作为参数传递来简化模板函数?

转载 作者:行者123 更新时间:2023-11-30 01:07:06 25 4
gpt4 key购买 nike

我写了一个小例子来说明这个问题。 solve_bs1_ysolve_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;
}

最佳答案

没有结构模板的包装器版本:

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>(...);

关于c++ - 通过将模板作为参数传递来简化模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45056524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com