How can I generate a list via the C preprocessor (cpp)?

前端 未结 5 2131
慢半拍i
慢半拍i 2020-12-09 11:12

I would like to do something like the following:

F_BEGIN

F(f1) {some code}
F(f2) {some code}
...
F(fn) {some code}

F_END

and have it gene

5条回答
  •  我在风中等你
    2020-12-09 11:50

    This is sort of abuse of CPP but a common type of abuse. I handle situations like this by defining dummy macros

    #define FUNCTIONS \
     foo(a,b,c,d) \
     foo(a,b,c,d) \
     foo(a,b,c,d)
    
    now, 
    
    #define foo(a,b,c,d) \
     a+b ;
    
    FUNCTIONS
    
    #undef foo
    

    later, when you want something different done with the same list

    #define foo(a,b,c,d) \
     a: c+d ;
    
    FUNCTIONS
    
    #undef foo
    

    It's a bit ugly and cumbersome, but it works.

提交回复
热议问题