C ++ Macro Copying Text

I would like to write a C ++ macro with an arbitrary argument, for example:

#define MANIP(...) \ //Implementation 

So what record

 MANIP(m_a, m_b, m_c); 

expands to

 f(a, b, c); g("a", "b", "c"); 

Is it possible?

Thank you in advance for your help in this seemingly extravagant question :)

+4
source share
4 answers

I do not believe that there will be an easy way from m_a to a . However, the stringize # operator is part of standard C and C ++.

for example given

 #define STRING(x) #x 

then STRING(m_a) will be converted to "m_a" .

+6
source
0
source

It is impossible to have a pre-processor (this is what processes the #define statements, not the C ++ compiler itself) breaks the arguments into pieces. Therefore, if you try to extract a from m_a , you cannot do this. Instead, it would be better to define your macro as:

  #define MANIP (m, a, b, c)

And you need the "m" to be a separate entrance.

Secondly, you cannot easily convert from non-string inputs to string inputs. IE, converting from a to "a" is not easy. I put it this way, because I know that some CPP (C-Pre-processor) can do this. But I do not think that it is tolerated.

Usually, when you try to do complex things, you should work with a programming language, not CPP.

In particular, in C ++ you have templates that will allow you to get much more work than the #define instructions for CPP.

0
source

The preprocessor cannot split tokens. This means that it is not possible to create foo from m_foo or (as was recently suggested) foo from "foo" .

If you can use variable macros (as Matti M. points out, that means C99 or C ++ 0x) Jens Gustedts P99 . There are macros to make it even easier, but lets make it accessible to people who are familiar with the library, OK?

A simplified case: there are two or three arguments.

 #define MANIP2(a, b) \ f(a, b) \ g(#a, #b) #define MANIP3(a, b, c) \ f(a, b, c) \ g(#a, #b, #c) #define MANIP(...) \ MANIP_( \ P99_PASTE2(MANIP, P99_NARG(__VA_ARGS__)), \ __VA_ARGS__) \ #define MANIP_(MANIPMAC, ...) MANIPMAC(__VA_ARGS__) 

This illustrates the basic principle. In practice, there are foreach-style macros (similar to Boosts) to simplify the code (although, as I mentioned, it is harder to read for the uninitiated). See P99 for details.

0
source

Source: https://habr.com/ru/post/1337525/


All Articles