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.
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.
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.
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.
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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With