user2088790
user2088790

Reputation:

templates with the datatypes: float, float4, float8, double, double4, int, int4, int8

I have the following data types defined: float, float4, float8, double, double4, int, int4, int8, long (64bit int), and long4. Let's assume I have the following functions defined:

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
}

The part that says "do something with f and i" is identical. So I don't want to write duplicate code. I wold like to instead do something like:

<float, 4>foo()

and this generates the function:

void foo() {
    float4 f;
    int4 i;
    ...do something with f and i
}

Any suggestions? Can I do this with templates? Or maybe a combination of define statements and templates?

Upvotes: 0

Views: 2164

Answers (3)

user2088790
user2088790

Reputation:

So a friend showed me how to do this in case anyone is interested. Now, if I pass a float4 to the function I get a int4 as well. I should add that int4 is data type with four integers (actually it corresponds to to a SSE register) not just a renaming of 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);
}

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249464

Sure, do this:

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

Invoke it like this:

foo<float4, int4>();

Upvotes: 3

NPE
NPE

Reputation: 500733

Yes, you can turn this group of functions into a single template function:

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

and then use it like so:

foo<float4, int4>();

Upvotes: 3

Related Questions