开发者

C++ metaprogramming with templates versus inlining

开发者 https://www.devze.com 2022-12-21 19:02 出处:网络
Is it worth to write code like the following to copy array elements: #include <iostream> using namespace std;

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 us开发者_运维问答e variables in the template.


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).


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.


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];


That's better because you control and enforce the loop unrolling by yourself.

A loop can be unrolled by the compiler depending on optimizing options...

The fact that copying with copy is almost the best is not a good general answer because the loop unrolling can be done whatever is the computation done inside...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号