C++ 数据类型为:float、float4、float8、double、double4、int、int4、int8的模板
我定义了以下数据类型:float、float4、float8、double、double4、int、int4、int8、long(64位int)和long4。假设我定义了以下函数:C++ 数据类型为:float、float4、float8、double、double4、int、int4、int8的模板,c++,templates,C++,Templates,我定义了以下数据类型: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_d
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
}
模板
void foo(){
f型浮球;
int_i型;
…用f和i做点什么
}
然后像这样使用它:
foo<float4, int4>();
foo();
当然,请执行以下操作:
template <typename Tf, typename Ti>
void foo() {
Tf f;
Ti i;
...do something with f and i
}
模板
void foo(){
tff;
TiⅠ;
…用f和i做点什么
}
像这样调用它:
foo<float4, int4>();
foo();
因此,一位朋友向我展示了如何在有人感兴趣的情况下做到这一点。现在,如果我把float4传递给函数,我也会得到一个int4。我应该补充一点,int4是具有四个整数的数据类型(实际上它对应于SSE寄存器),而不仅仅是int的重命名
template <typename F> struct Tupple {
};
template<> struct Tupple<float> {
typedef int Intn;
};
template<> struct Tupple<float4> {
typedef int4 Intn;
};
template<> struct Tupple<float8> {
typedef int8 Intn;
};
template<> struct Tupple<double4> {
typedef long4 Intn;
};
template <typename Floatn>
void foo(typename Floatn a) {
typename Tupple<Floatn>::Intn i;
Floatn b;
i = (a < b);
//do some more stuff
}
int main() {
float4 a;
float8 b;
float c;
double4 d;
foo(a);
foo(b);
foo(c);
foo(d);
}
模板结构元组{
};
模板结构元组{
typedef-int-n;
};
模板结构元组{
typedef int4 Intn;
};
模板结构元组{
typedef int8 Intn;
};
模板结构元组{
typedef long4 Intn;
};
样板
void foo(类型名Floatn a){
typename tuple::Intn i;
漂浮蛋白b;
i=(a
有foo()
不是很好吗?谢谢。我会尽力的。我想我试过了,但对某些事情不满意,但我会再试一次。一个问题是它不能保护我不意外地做foo或foo。对于floatn和intn,我希望n和n的值相等。然后,如果它们不匹配,代码也不会编译,所以可能没问题。