Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ metaprogramming with templates versus inlining

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.

like image 276
cibercitizen1 Avatar asked Mar 04 '10 14:03

cibercitizen1


People also ask

What are drawbacks of using templates and metaprogramming?

Although we can gain benefits from template metaprogramming, there are several disadvantages, which are as follows: The syntax is quite complex. The compilation time takes longer since we now execute code during compile-time.

Why is template metaprogramming useful?

So, using templates, we can write programs that do computation at compile time, such programs are called template metaprograms. Template metaprogramming is in fact Turing-complete, meaning that any computation expressible by a computer program can be computed, in some form, by a template metaprogram.

Are templates compile-time or runtime?

Unfortunately, this isn't possible because i is only available at runtime, while templates are compiled at compile time. This is a very important concept to understand when dealing with templates in C++: templates don't exist at runtime. All templates are compiled to real types at compile time.

What is template based Programming?

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.


1 Answers

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

like image 156
Johannes Schaub - litb Avatar answered Oct 06 '22 00:10

Johannes Schaub - litb