cib*_*en1 5 c++ templates metaprogramming
是否值得编写如下代码来复制数组元素:
#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;
   }
} // () 
或者使用内联函数更好?
第一个缺点是您不能在模板中使用变量.
那不是更好.首先,它不是真正的编译时间,因为你在这里进行函数调用.如果幸运的话,编译器会内联这些内容并最终得到一个循环,你可以用更少量的代码(或者只是使用std::copy)自己编写.
| 归档时间: | 
 | 
| 查看次数: | 1333 次 | 
| 最近记录: |