C / C ++ macro extension against code generation

Both the Macro extension and code generation have pros and cons. What is your favorite approach and why? When should we choose one by one? I ask you to advise. Thanks!

Macro extension can be very convenient and useful: http://dtemplatelib.sourceforge.net/table.htm

against

While code generation gives you a lot of nice code: http://code.google.com/p/protobuf/ http://incubator.apache.org/thrift/

+6
c ++ macros code-generation
source share
4 answers

This is a compromise. Let me give you an example. I came across differential execution technique in 1985, and I find this to be a really good tool for programming user interfaces. Basically, this requires simple structured programs:

void Foo(..args..){ x = y; if (..some test..){ Bar(arg1, ...) } while(..another test..){ ... } ... } 

and mucks with a management structure like this:

 void deFoo(..args..){ if (mode & 1){x = y;} {int svmode = mode; if (deIf(..some test..)){ deBar(((mode & 1) arg1 : 0), ...) } mode = svmode;} {int svmode = mode; while(deIf(..another test..)){ ... } mode = svmode;} ... } 

Now a really good way to do this is to write a parser for C or any other base language, and then go through the parse tree, generating the code I want. (When I did this in Lisp, this part was simple.)

But who wants to write a parser for C, C ++ or something else?

So, instead, I just write macros to write code like this:

 void deFoo(..args..){ PROTECT(x = y); IF(..some test..) deBar(PROTECT(arg1), ...) END WHILE(..another test..) ... END ... } 

However, when I do this in C #, some of their wisdom decided that the macros were bad and I don’t want to write a C # parser, so I have to do the code generation manually. This is a royal pain, but it is still worth what can be compared to the usual way of encoding these things.

+2
source share

For C ++, I prefer metaprogramming templates or generating code over macros, but macros still use them.

The example you provided with dbtemplatelib can be covered with C ++ 0x Variadic Templates with additional benefits such as type checking, etc.

+9
source share

In C or C ++, macro expansion is notoriously difficult to debug. On the other hand, writing a code generator is easier to debug, because it is a separate program in itself.

However, you should know that this is just a limitation of the C preprocessor. For example, in the Lisp language family, the macro extension is code generation, they are exactly the same. To write a macro, you write a program (in Lisp) to convert the input of an S-expression to another S-expression, which is then passed to the compiler.

+5
source share

Both have their own problems. Unlike macros, code generation can produce readable and debugged (is it even a word?) Code, but it is less flexible and harder to change.

+3
source share

All Articles