Re: 2 variable "nested" loop with TMP

From: Rob Williscroft (rtw_at_freenet.co.uk)
Date: 05/25/04


Date: 25 May 2004 18:38:09 GMT

Robin Eidissen wrote in news:c8vs7v$93n$1@orkan.itea.ntnu.no in
comp.lang.c++:

> What I try to do is to iterate over two variables using template
> metaprogramming. I've specialized it such that when it reaches the end
> of a row ot starts on the next and when it reaches the last row it
> stops.. At least that's what I thought I did, but VC71 says "warning
> C4717: 'LOOP<0,1>::DO' : recursive on all control paths, function will
> cause runtime stack overflow".
> What's wrong?
>
> Here's the code:
> template<int M, int N>
> class LOOP {

> public:
> static inline void DO() {

inline here is unnessacery function's defined inside a class
are always inline.

> };
>

With some correction's I got your version to work with an EDG compiler
but I couldn't be bothered wating for VC 7.1 to run out of memory,
g++ (3.4), didn't compile it either.

This seems to work though:

#include <iostream>
#include <ostream>

template< int M, int N, int I = M, int J = N >
struct loop
{
  template < typename F >
  static void apply( F f )
  {
    f( M - I, N - J );
    loop<M, N, I, J - 1>::apply( f );
  }
};

template< int M, int N, int I >
struct loop< M, N, I, 0 >
{
  template < typename F >
  static void apply( F f )
  {
    loop<M, N, I - 1, N>::apply( f );
  }
};

template< int M, int N, int J >
struct loop< M, N, 0, J >
{
  template < typename F >
  static void apply( F )
  {
  }
};

void function( int i, int j )
{
  std::cout << "(" << i << "," << j << ") ";
}

int main()
{
  loop<3, 3>::apply( function );
}

HTH.

Rob.

-- 
http://www.victim-prime.dsl.pipex.com/


Relevant Pages