Boost logo

Boost :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2002-09-26 09:42:19


On Thursday 26 September 2002 03:23 am, Gennadiy Rozental wrote:
> Let say I have one global array int stat[100][100]. And want to write an
> initializer for it that follow formula like this:
>
> if j2 > j >= j1 && i2 > i >= i1
> x[i][j] = i - i1;
> else
> x[i][j] = 0
>
> Or something similar.
>
> Obviously I could type all the elements, but it's inconvenient, difficult
> to change and error prone. Could MPL or BOOST_PP be of some help here?

The preprocessor library can do this. The result would look something like
this, but beware the untested code:

#define STAT_ELEMENT(J,I) \
  BOOST_PP_IF(BOOST_PP_AND(\
    BOOST_PP_AND(BOOST_PP_GREATER(J2,J),BOOST_PP_GREATER_EQUAL(J,J1)), \
    BOOST_PP_AND(BOOST_PP_GREATER(I2,I),BOOST_PP_GREATER_EQUAL(I,I2))),\
    I - I1, \
    0)

#define STAT_LINE(I,UNUSED) \
  { BOOST_PP_ENUM(100,STAT_ELEMENT,I) }

int stat[100][100] = {
  BOOST_PP_ENUM(100,STAT_LINE,BOOST_PP_EMPTY)
};

I didn't have any idea where I1, I2, J1, and J2 came from, so they are just
assumed to be macros. However, you could package them in a tuple if they need
to be passed in.

        Doug


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk