C ++ metaprogramming模板与内联 [英] C++ metaprogramming with templates versus inlining

查看:164
本文介绍了C ++ metaprogramming模板与内联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有必要编写如下代码来复制数组元素:

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

} // () 

更好地使用内联函数?

第一个缺点是你不能在模板中使用变量。

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

推荐答案

这不是更好。首先,它不是真正的编译时间,因为你在这里进行函数调用。如果你很幸运,编译器会内联这些,最后是一个循环,你可以用更少的代码写自己(或只是使用 std :: copy

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

这篇关于C ++ metaprogramming模板与内联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆