问题描述
受这种解决方案的启发,我编写了下面的代码,用于模拟宏的重载" .
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;
}
此工作正常以g ++/铛++编译器,给下面的输出:
This works fine in g++/clang++ compilers, giving below output:
1 argument
2 arguments
3 arguments
然而,它没有给出预期输出最新MSVC(2017)由于与已知的编译器故障:
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
我尝试过各种间接扩张"的组合,基于以下职位,但没有运气:点击视觉工作室__VA_ARGS__问题
I tried various "indirect expansions" combinations, based on below post, but no luck:
Visual studio __VA_ARGS__ issue
如何解决这个问题的MSVC?
How to fix this issue in MSVC?
推荐答案
我对MSVC错误的了解不是很丰富,除了知道它存在之外,但我能够在其他答案中应用替代方法如下:
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__)
此也产生最新的GCC和锵适当预处理器输出.它不会让我感到吃惊地得知,有一种方法可以解决此而不调用宏间接扩张"两次,但我没有找到它.
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.
这篇关于如何解决与"可变参数宏的相关问题;宏观超载"在MSVC ++(Microsoft Visual Studio)中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!