我定义了以下数据类型:float、float4、float8、double、double4、int、int4、int8、long(64 位 int)和 long4。假设我定义了以下函数:
void foo_float() {
float f;
int i;
...do something with f and i
}
void foo_float4() {
float4 f;
int4 i;
...do something with f and i
}
void foo_double4() {
double4 f;
int4 i;
...do something with f and i
}
“用 f 和 i 做某事”的部分是相同的。所以我不想写重复的代码。我想改为做类似的事情:
<float, 4>foo()
这会生成函数:
void foo() {
float4 f;
int4 i;
...do something with f and i
}
有什么建议吗?我可以使用模板执行此操作吗?或者可能是定义语句和模板的组合?
最佳答案
是的,您可以将这组函数变成一个模板函数:
template<typename float_type, typename int_type>
void foo() {
float_type f;
int_type i;
...do something with f and i
}
然后像这样使用它:
foo<float4, int4>();
关于c++ - 数据类型为 : float, float4、float8、double、double4、int、int4、int8 的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15597645/