Search code examples
metaprogrammingwxwidgetsc-preprocessor

How to use of code chunks as parameters to c preprocessor directives?


Is there a way to provide a macro with entire chunks of code as a parameter and expand it into the definition?

#define PATTERN(param,func)\
    chk=new wxCheckBox(page,wxID_ANY,param);\
    sizer->Add(chk,0,0,0);\
    chk->Bind(wxEVT_CHECKBOX,func);

PATTERN("checkbox 1",
 //piece of code
 [=](wxCommandEvent& event){
   wxMessageBox(wxT("test"),wxT(""),wxICON_INFORMATION);
  }
 //end of code
)

How to encapsulate code for these means? I want to be able to do:

   #define DERIVATIVE(s)\
      PATTERN(...)

Solution

  • You're better off using two sets of macros for this

    #define TEMPLATE_CODE(INSERTME) \
      ... \
      INSERTME(); \
      ...
    
    #define SPECIALIZED_CODE() \
      ...
    
    TEMPLATE_CODE(SPECIALIZED_CODE);
    

    As an example,

    #define TEMPLATE_CODE(INSERTME, ARG) void sayhello(void) { INSERTME(ARG); }
    #define OTHER_TEMPLATE(INSERTME, ARG) class myclass { INSERTME(ARG); }
    #define FIRST_IMPL(ARG) cout << ARG << endl
    #define WRAPPER() TEMPLATE_CODE(FIRST_IMPL, ARG)
    OTHER_TEMPLATE(WRAPPER, "hello world")
    #undef FIRST_IMPL
    #undef WRAPPER