I would like to know if it is possible to have a for loop in compile time with runtime or even compile time limit condition in c++11
I don't know a reasonable way to have such loop with a runtime condition.
With a compile time condition... If you can use at least C++14, you can use a solution based on std::integer_sequence
/std::make_integer_sequence
(see Caleth answer) or maybe std::index_sequence
/std::make_index_sequence
(just a little more synthetic).
If you're limited with C++11, you can create a surrogate for std::index_sequence
/std::make_index_sequence
or you can create a recursive template struct with static function (unfortunately you can partially specialize a template function but you can partially specialize classes and structs).
I mean... something as follows
template <std::size_t I, std::size_t Top>
struct for_loop
{
static void func ()
{
templated_func<I>();
for_loop<I+1u, Top>::func();
}
};
template <std::size_t I>
struct for_loop<I, I>
{ static void func () { } };
that you can call
constexpr auto n = 10u;
for_loop<0, n>::func();
if you want to call templated_func()
with values from zero to n-1u
.
Unfortunately this solution is recursive so you can have troubles with compilers recursion limits. That is... works only if n
isn't high.