Search code examples
c++boostforeachmacrospreprocessor

How to use BOOST_PP_SEQ_FOR_EACH for execting a function for each in the sequence?


I intend to use BOOST_PP_SEQ_FOR_EACH to run a function for all variables of a sequence:

#include <iostream>
#include <boost/preprocessor.hpp>
#include <boost/preprocessor/seq/for_each.hpp>


#define SEQ (w)(x)(y)(z)
#define MACRO(r, data, elem) foo(#elem);

using namespace std;


void foo(string a) {
  cout << a << endl;
}


int main(){


  BOOST_PP_SEQ_FOR_EACH(MACRO, ,SEQ) ;


  return 0 ;
}

The expected output is like:

w
x
y
z

, while the actual result is:

BOOST_PP_SEQ_HEAD((w)(x)(y)(z))
BOOST_PP_SEQ_HEAD((x)(y)(z))
BOOST_PP_SEQ_HEAD((y)(z))
BOOST_PP_SEQ_HEAD((z))

I don't know what happens to the expansion. I am thinking BOOST_PP_SEQ_FOR_EACH clause is expanded into

MACRO(r, ,w) MACRO(r, ,x) MACRO(r, ,y) MACRO(r, ,z)

and MACRO(r, ,w) is expanded into foo("w"); for instance.


Solution

  • BOOST_PP_SEQ_HEAD((a)(b)(c)) is a macro to get the head of a preprocessor sequence and would expand to a. But #elem prevents that macro from being expanded.

    Use BOOST_PP_STRINGIZE to expand the macro as well:

    #define MACRO(r, data, elem) foo(BOOST_PP_STRINGIZE(elem));