I am working with a library which exposes an interface to work with. One of the functions of this library is like this :
template
void modify()
What is the value of i (that is not a constant) at compile time? There is no way to answer unless executing the loop. But executing is not "compiling" Since there is no answer, the compiler cannot do that.
Templates are not algorithm to be executed, but macros to be expanded to produce code. What you can do is rely on specialization to implement iteration by recursion, like here:
#include
template
void modify()
{ std::cout << "modify<"<"<< std::endl; }
template
struct static_for
{
void operator()()
{ modify(); static_for()(); }
};
template
struct static_for
{
void operator()()
{}
};
int main()
{
static_for<0,10>()();
}
Note that, by doing this, you are, in fact, instantiating 10 functions named
modify<0>
... modify<9>
, called respectively by static_for<0,10>::operator()
... static_for<9,10>::operator()
.
The iteration ends because static_for<10,10>
will be instantiated from the specialization that takes two identical values, that does nothing.