tags:

views:

63

answers:

4

Is there a way to do


#define  A f1();
#define A A f2();  // this is wrong
#define A A f3(); // this is wrong
...
#define A A fn(); // this is wrong

A 

and then get


f1(); f2(); f3();  ... fn();

A: 

Yes.

#define  A f1();
#define B A f2();  // this is right

B 
Svisstack
I need to accumulate the definition in A. When I write A, I won't know how many times A has been incremented before.
cibercitizen1
+1  A: 

You could use the boost preprocessor library. It can iterate macros and much more:

http://www.boost.org/doc/libs/1_43_0/libs/preprocessor/doc/index.html

EDIT: I read your comment and will stay tuned for solutions easier than the following code ;-) :

#include <boost/preprocessor/repetition/repeat.hpp>
#define A(z, n, text) text ## n = 0;
BOOST_PP_REPEAT(3, A, int x)

which generates

int x0 = 0; int x1 = 0; int x2 = 0;

Note that this is not a strict solution as it does not define a macro that repeats another macro but repeats an already defined macro.

Peter G.
For me, boost is too complicated, and I just need this only feature.
cibercitizen1
Thanks for your interest, but, still this is not what I need: the macro A should be incremented in several steps.
cibercitizen1
A: 

When you write

#define foo [something]

if an occurence of foo is found in the [something], it is simply ignored.

So it seems you cannot do recursion with the preprocessor, and use ugly hacks like BOOST_REPEAT, which "teaches the preprocessor how to count" by listing ugly macros. What you are asking for is not simple to do without BOOST_REPEAT.

Alexandre C.
OK, so you wouldn't recommend reading how BOOST_REPEAT has been done?
cibercitizen1
for having trying to implement such a thing, definitely no.
Alexandre C.
A: 
#define A f1();

...

#define TEMP_A A
#undef A
#define A TEMP_A f2();
#undef TEMP_A

...

Though I suggest that you consider doing it as:

#define A f1()
// Note the lack of the semicolon

...

#define TEMP_A
#undef A
#define A do { TEMP_A; f2(); } while (0)
#undef TEMP_A

Since that would both allow and force you to use semicolons correctly when you call the macros in code.

It gets more complicated if your functions are returning values and you want to access these values, but then you should investigate the use of the coma operator.

#define A (( TEMP_A, f2() ))

This would allow you to have A return the value returned by f2() after running TEMP_A, which is f1(). The double parenthesis make it so that if you do something silly like:

printf A;

it doesn't try to treat it as an an argument list and only as a single argument.

nategoose
The firs code snipet doesn't work it yields (after substitution, with g++ -E) TEMP_A f2();
cibercitizen1
The second code snipet doesn't work either. I produces:do { TEMP_A; f2(); } while (0)
cibercitizen1