Search code examples
c++11templatesfor-loopmetaprogrammingcompile-time

Is that possible to have a for loop in compile time with runtime or even compile time limit condition in c++11?


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 start with a silly try to find out what I need.

for (uint32_t i = 0; i < n; ++i)
  {
    templated_func<i>();
  }

consider I have a class with a private member variable n, and I want to call a template function with a different number that iterates from 0 to n (for the case of runtime limit condition) I've had studies on the "Template Metaprogramming" and "Constexpr If" (c++17) but I have not gotten any results, can anyone help me?


Solution

  • 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.