C++ template techniques for straightening out recursion?

时间:2017-11-08 22:08:25

标签: c++ templates recursion design-patterns

Assume I have a function that has a naturally occurring recursion, but I want to avoid to do recursion for any number of reasons. Do there exist any good ways to apply templates in C++ to systematically reshape the code execution to avoid the possible hazards of recursion?


An example, we can assume T1, T2 are some types and start(), end() some arbitrary functions taking arguments and returning things of the respective types:

T2 recursion(T1 a1){
  T1 l1 = start(a1);
  if( recurse_condition(a1,l1) )
     T2 l2 = recursion(l1);
  else return final(a1,l1);
  return end(l2);
}

So if I understand tail-recursion right it would be possible to do only if the end() function did nothing, but we assume here that it might do something.


(I am not extremely frequently on this site so feel free to redirect me if question is more suitable somewhere else.)

1 个答案:

答案 0 :(得分:1)

鉴于你的例子(稍加纠正)

template <typename T2, typename T1>
T2 recursion(T1 a1){
  T1 l1 = start(a1);
  if( recurse_condition(a1,l1) )
     T2 l2 = recursion<T2>(l1);
  else return final(a1,l1);
  return end(l2);
}

我想你可以避免像(也是C ++ 98)

这样的递归
template <typename T2, typename T1>
T2 noRecursion (T1 a1)
 {
   std::size_t cnt ( 0U ); // counter: how many time is
                           // executed `start()`

   T1 l1 ( a1 );

   do
    {
      a1 = l1;
      l1 = start(a1);

      ++cnt;
    }
   while ( recurse_condition(a1, l1) );

   T2 l2 ( final(a1, l1) );

   // exec end() one time less than start()
   while ( --cnt ) // shorter than for (auto ui = 1U ; ui < cnt ; ++ui)
      l2 = end(l2);

   return l2;
 }

在这种情况下,模板方面(T1T2)独立于递归/非递归方面:如果在递归版本中有用,则在非递归函数中很有用。