Search code examples
c++cmacrosc++builder-xe2

Macro: How do I change each value in __VA_ARGS__


I am using C++ Builder XE3.

Currently I have such macro as below:

#define LOGG(message, ...) OTHER_LIB_LOG(message,__VA_ARGS__)

Now I want to make all arguments be AnsiString. It is easy for me to deal with the argument: message like below:

#define LOGG(message, ...) OTHER_LIB_LOG(AnsiString(message),__VA_ARGS__)

But for VA_ARGS, I do not know how to deal with the arguments to make sure all arguments which are put to OTHER_LIB_LOG are AnsiString.

It is hard for me to modify the source code of OTHER_LIB_LOG, so I have to do this with Macro.

Any help will be appreciated.


Solution

  • C macros don't recurse. So you will have to do some manual work.
    Find the max number of arguments LOGG will take & use as below: My example takes max 6 arguments.

    #define ENCODE0(x) AnsiString(x)
    #define ENCODE1(x,...) AnsiString(x), ENCODE0(__VA_ARGS__)
    #define ENCODE2(x,...) AnsiString(x), ENCODE1(__VA_ARGS__)
    #define ENCODE3(x,...) AnsiString(x), ENCODE2(__VA_ARGS__)
    #define ENCODE4(x,...) AnsiString(x), ENCODE3(__VA_ARGS__)
    #define ENCODE5(x,...) AnsiString(x), ENCODE4(__VA_ARGS__)
    #define ENCODE6(x,...) AnsiString(x), ENCODE5(__VA_ARGS__)
    //Add more pairs if required. 6 is the upper limit in this case.
    #define ENCODE(i,...) ENCODE##i(__VA_ARGS__) //i is the number of arguments (max 6 in this case)
    
    #define LOGG(count,...) OTHER_LIB_LOG(ENCODE(count,__VA_ARGS__))
    

    Sample Usage: LOGG(5,"Hello","Hi","Namaste _/\_","Hola!","bonjour");