views:

250

answers:

3

Is it worth to write code like the following to copy array elements:

#include <iostream>
using namespace std;


template<int START, int N> 
struct Repeat { 
  static void copy (int * x, int * y) {
   x[START+N-1] = y[START+N-1];
   Repeat<START, N-1>::copy(x,y);
  }
};

template<int START> 
struct Repeat<START, 0> { 
  static void copy (int * x, int * y) {
   x[START] = y[START];
  }
};



int main () {


   int a[10];
   int b[10];

             // initialize
   for (int i=0; i<=9; i++) {
     b[i] = 113 + i;
     a[i] = 0;
   }

            // do the copy (starting at 2, 4 elements)
  Repeat<2,4>::copy(a,b);

             // show
   for (int i=0; i<=9; i++) {
   cout << a[i] << endl;
   }

} // () 

or is it better to use a inlined function?

A first drawback is that you can't use variables in the template.

+5  A: 

That's not better. First of all, it's not really compile time, since you make function calls here. If you are lucky, the compiler will inline these and end up with a loop you could have written yourself with much less amount of code (or just by using std::copy).

Johannes Schaub - litb
+1 f*ck yeah ! !
Tom
This is just not true. The recursion is compile-time, there is no runtime recursion here. Each function is of a different class, and is just not the same function. What would say would be true for Java though!
PierreBdR
@PierreBdr, it is true that a different function is involved each time. But these are function calls done at runtime, and the effect is as if you would call the same function in a recursive manner (as opposed to *true* compile time recursion ala' `static int const value = Class<N-1>::value + 1;`). The only difference is that the end condition can be evaluated at compile time. But so can the condition of an equivalent loop.
Johannes Schaub - litb
@PierreBdr, i've removed the part that stated that this is a recursive function, as i agree with you that was misleading.
Johannes Schaub - litb
I read the assembler code generated and seems something like:copy_first: mov ... mov ... call copy_secondcopy_second: mov ... mov ... call copy_thirdcopy_third: mov ... mov....The code will do the same just removing the calls !
cibercitizen1
A: 

You shouldn't do this. Templates were invented for different purpose, not for calculations, although you can do it. First you can't use variables, second templates will produce vast of unused structures at compilation, and third is: use for (int i = start; i <= end; i++) b[i] = a[i];

Andrey
Yes, templates were invented for different purpose, but you just can't imagen how many books writte and e-ink used for that second non-intendend use !
cibercitizen1
Yep, don't make claims about templates that you cannot substantiate.
Hassan Syed
+1  A: 

General rule: Use templates for things known at compile time, use inlining for things known at run time. If you don't know the size of your array at compile time, then don't be using templates for it.

miked