数据类型的模板:float,float4,float8,double,double4,int,int4,int8

时间:2013-03-24 11:02:40

标签: c++ templates

我定义了以下数据类型:float,float4,float8,double,double4,int,int4,int8,long(64bit 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
}

有什么建议吗?我可以使用模板吗?或者可能是定义语句和模板的组合?

3 个答案:

答案 0 :(得分:3)

是的,您可以将这组功能转换为单个模板功能:

template<typename float_type, typename int_type>
void foo() {
  float_type f;
  int_type i;
  ...do something with f and i
}

然后像这样使用它:

foo<float4, int4>();

答案 1 :(得分:3)

当然,这样做:

template <typename Tf, typename Ti>
void foo() {
  Tf f;
  Ti i;
  ...do something with f and i
}

像这样调用它:

foo<float4, int4>();

答案 2 :(得分:1)

所以如果有人有兴趣,朋友会告诉我如何做到这一点。现在,如果我将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);
}