C++:在 Visual Studio 中处理每个可变参数

标签 c++ visual-c++ macros c-preprocessor

试图让它在 VS2013 中工作(参见 Variadic macro trickC++ preprocessor __VA_ARGS__ number of arguments)。

这不是重复的 afaik(其他地方发布的版本仅适用于 GCC)。

知道这有什么问题吗?我快到了...

#define _EXPAND(x) x
#define _VA_NARGS_IMPL(_1_, _2_, _3_, _4_, _5_, N, ...) N
#define _VA_NARGS_IMPL2(...) _EXPAND(_VA_NARGS_IMPL(__VA_ARGS__, 4, 3, 2, 1, 0))
#define _PUSH_X_FRONT(...) X, __VA_ARGS__
/*
Returns the number of arguments specified.
#ifndef _MSC_VER
  #define VA_NARGS(...)  _VA_NARGS_IMPL2(X,##__VA_ARGS__)
*/
#define VA_NARGS(...)  _VA_NARGS_IMPL2(_PUSH_X_FRONT(__VA_ARGS__))

// testing is gewd
static_assert(VA_NARGS() == 0, "VA_NARGS() failed for 0 arguments");
static_assert(VA_NARGS(one, two, three, four) == 4, "VA_NARGS() failed for 4 arguments");

#define _VARARG_IMPL2(N, Macro, ...) Macro##N(__VA_ARGS__)
#define _VARARG_IMPL(N, Macro, ...) _VARARG_IMPL2(N, Macro, __VA_ARGS__)
// Helper function for variadic macros with per-argument processing.
#define VARARG(Macro, ...) _VARARG_IMPL(VA_NARGS(__VA_ARGS__), Macro, __VA_ARGS__)


#define _Quote1(x) #x
#define _Quote2(x, ...) #x, _Quote1(__VA_ARGS__)
#define _Quote3(x, ...) #x, _Quote2(__VA_ARGS__)
#define _Quote4(x, ...) #x, _Quote3(__VA_ARGS__)
// Treat each argument as a string literal, encompassing in quotes.
#define Quote(...) VARARG(_Quote, __VA_ARGS__)

问题:

constexpr char *a[] = { Quote(a, b) };
// WHY does the above produce {"a, b"} with msvc?
// The following produces {"a", "b"} as expected
constexpr char *a[] = { _Quote2(s, c) };

最佳答案

很难使真正的可变参数宏在 VS2013 中工作。我做了一些事情来扩展一个宏,让它自己被解释为一个新的宏。关键是制作多级宏。代码量很大,但对于给定的示例,它会起作用。

#define InitialMacro (argument1, argument2) \
DetailedMacro(argument1, argument2, argument1##_description, argument2##_description)

#define DetailedMacro (argument1, argument2, argument3, argument4)      \
L#argument1     \
L#argument2     \
L#argument3     \
L#argument4

这里提出的想法是实现足够多的宏来满足您对所需参数数量的所有要求。您也可以在途中转发/更新带有其他项目的宏。 基本上,此示例中的第一个宏将后缀 _description 附加到第二个和第三个传输参数,从而生成另一个宏,该宏将被解释为宏,并将在 DetailedMacro 中展开。

你也可以看看这个:msvc variadic macro expansion

关于C++:在 Visual Studio 中处理每个可变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37853530/

相关文章:

macros - 可以使用宏扩展为构造函数元组吗?

c++ - std::string[] 成员释放在从构造函数抛出异常期间失败

C++ cURL 链接错误 "unresolved external symbol _curl_easy_"

c++ - 为什么 sizeof(intArray)/sizeof(int) 给出不同的值?

c++ - 编译一个简单程序的Boost Date_Time问题

c++ - std::forward Visual Studio 13 的行为与我预期的不同

c++ - 如何让 ToolTip 出现在 float 的 CPaneDialog 的最前面?

c++ - 使用默认参数的宏包装函数调用

text - 我怎样才能使用格式! no_std 环境中的宏?

当我访问下一个 Node 指针时,C++ 崩溃