I want to be able to create an array of calculated values (let\'s say for simplicity\'s sake that I want each value to be the square of it\'s index) at compile time using t
I'm not sure whether you want to see it done or find a library that will just do it for you. I assume the former.
template
struct SqArr {
static inline void fill(int arr[]) {
arr[N-1] = (N-1)*(N-1);
SqArr::fill(arr);
}
};
template<>
struct SqArr<0> {
static inline void fill(int arr[]) { }
};
Now let's try to use this beast:
#include
#include
#include
using namespace std;
int main(int argc, char* argv[])
{
int arr[10];
SqArr<10>::fill(arr);
cout << endl;
copy(arr, arr+10, ostream_iterator(cout, "\t"));
cout << endl;
return 0;
}
Note (confession): This isn't compile-time computation. To motivate that you can try to change the fourth line from SqArr to SqArr so the recursion is infinite, and you will see this compiles fine (when the compiler should in fact recurse indefinitely, or complain about the infinite recursion).