问题
Inspired from this kind of solution, I have written below code, which simulates "overloading of macros".
#include<iostream>
#define CONCATE_(X,Y) X##Y
#define CONCATE(X,Y) CONCATE_(X,Y)
#define UNIQUE(NAME) CONCATE(NAME, __LINE__)
#define NUM_ARGS_(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, TOTAL, ...) TOTAL
#define NUM_ARGS(...) NUM_ARGS_(__VA_ARGS__, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
#define VA_MACRO(MACRO, ...) CONCATE(MACRO, NUM_ARGS(__VA_ARGS__))(__VA_ARGS__)
#define COUT(...) VA_MACRO(_COUT, __VA_ARGS__)
#define _COUT1(X) std::cout << "1 argument\n"
#define _COUT2(X, Y) std::cout << "2 arguments\n"
#define _COUT3(X, Y, Z) std::cout << "3 arguments\n"
int main ()
{
COUT("A");
COUT("A", 1);
COUT("A", 1, 'a');
return 0;
}
This works fine in g++/clang++ compilers, giving below output:
1 argument
2 arguments
3 arguments
However it doesn't give the expected output for latest MSVC (2017) due to known compiler bug related to __VA_ARGS__
:
1 argument
1 argument
1 argument
I tried various "indirect expansions" combinations, based on below post, but no luck:
Visual studio __VA_ARGS__ issue
How to fix this issue in MSVC?
回答1:
I'm not very experienced with the MSVC bug other than knowing it exists, but I was able to apply the workaround in the other answer as follows:
#define MSVC_BUG(MACRO, ARGS) MACRO ARGS // name to remind that bug fix is due to MSVC :-)
#define NUM_ARGS_2(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, TOTAL, ...) TOTAL
#define NUM_ARGS_1(...) MSVC_BUG(NUM_ARGS_2, (__VA_ARGS__))
#define NUM_ARGS(...) NUM_ARGS_1(__VA_ARGS__, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
#define VA_MACRO(MACRO, ...) MSVC_BUG(CONCATE, (MACRO, NUM_ARGS(__VA_ARGS__)))(__VA_ARGS__)
This also produces appropriate preprocessor output on the latest GCC and Clang. It would not surprise me to learn that there's a way to work around this without calling MSVC_BUG
macro for "indirect expansion" twice, but I didn't find it.
来源:https://stackoverflow.com/questions/48710758/how-to-fix-variadic-macro-related-issues-with-macro-overloading-in-msvc-mic