Macro to create multiple similar identifiers for testing

49 Views Asked by At

I wanted to write a simple macro to expand some identifiers so it saves me the work of typing everything again and again when I have similar code to test for many different classes.

I wanted something like this:

#define TST(x)  x## x##_1(2);                   \
                x## x##_2;                      \
                                                \
                x##_1.print(cout);              \
                x##_2.print(cout);              \
                x##_2.elem(3);                  \
                x##_2.elem(4);                  \
                x##_2.print(cout)

To be translated into

Pentagonal Pentagonal_1(2);
Pentagonal Pentagonal_2;

Pentagonal_1.print(cout);
Pentagonal_2.print(cout);
Pentagonal_2.elem(3);
Pentagonal_2.elem(4);
Pentagonal_2.print(cout);

whenever I call

TST(Pentagonal);

so far it is being translated glued together like

PentagonalPentagonal_1

I tried searching for this but in this specific case I couldn't find much help elsewhere.

1

There are 1 best solutions below

1
On BEST ANSWER

Change:

#define TST(x)  x## x##_1(2);                   \
                x## x##_2;                      \

...

to

#define TST(x)  x x##_1(2);                   \
                x x##_2;                      \

...

## is the token-paste operator: It "absorbs" surrounding whitespace and joins neighboring tokens into one.

The extras you had up there were pasting the Pentagonal and Pentagonal_1 together.