Search code examples
c++boostboost-preprocessor

Preprocessor: How to use a list to definition of variables and function input


I have three lists one with integer variables (ilist), one with double variables (dlist) and one with std::string variables (slist) with specific initial values. Example: ilist=(ilist1=init_val_1)(ilist2=init_val_2)

Is it possible for the preprocessor to generate code like:

int ilist1=init_val_1;
int ilist2=init_val_2;
...
int ilistn=init_val_n;

double dlist1=dnit_val_1;
double dlist2=dnit_val_2;

f(ilist1, ilist2, ilist3, ..., ilistn, dlist1, dlist2);

I can use boost (boost::preprocessor) in this project.


Solution

  • When I was just first starting programming, I was always looking for ways to quickly and safely define lots of similar variables. Now, I realise that, almost invariably, it is better to use an array, std::array or std::vector instead - it's much more readily understandable and easy to use, even if there is some nasty hacky way of doing it with the pre-processor.

    FWIW, this immediately sprang to mind:

    #define I(x) int ilist##x=init_val_##x
    I(1);
    I(2);
    //[...]
    
    #undef I //to avoid accidentally using it later in the code
    #define D(x) double dlist##x=dnit_val_##x;
    D(1);
    D(2);
    #undef D 
    

    Functions that need lots of variables like this almost certainly want an array, std::array or std::vector or two really.