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
It's called Static Table Generation in metaprogramming.
#include
const int ARRAY_SIZE = 5;
template
class Table : public Table
{
public:
static const int dummy;
};
template
class Table
{
public:
static const int dummy;
static int array[N];
};
template
const int Table::dummy = Table::array[I] = I*I + 0*Table::dummy;
template
int Table::array[N];
template class Table;
int main(int, char**)
{
const int *compilerFilledArray = Table::array;
for (int i=0; i < ARRAY_SIZE; ++i)
std::cout<
We use explicit template instantiation and a dummy variable to force the compiler to fill the array with index squares. The part after I*I is the trick needed to recursively assign each array elements.