In some contexts, it could be useful/necessary to have a for
loop evaluated/unrolled at compile time. For example, to iterate over the elements of a tuple
I'll answer on the question how to fix your last code sample.
The reason why it doesn't compile is here:
template class F, typename... Args>
void compile_time_for(F f, Args... args)
/\
F is a template, you can't have an object of a template class without template parameters being substituted. E.g. you can't have on object of std::vector
type, but can have object of std::vector
. I suggest you to make F
functor with a template operator() :
#include
#include
#include
#include
template
void compile_time_for(F f, Args... args)
{
if constexpr (start < end)
{
f.template operator()(std::forward(args)...);
compile_time_for(f, std::forward(args)...);
}
}
struct myprint
{
template
void operator()(const std::tuple& x) { std::cout << std::get(x) << " "; }
};
int main()
{
std::tuple x{1, 2, "hello"};
compile_time_for<0, 3>(myprint(), x);
return 0;
}