相关疑难解决方法(0)

在参数数量上重载宏

我有两个宏,FOO2并且FOO3:

#define FOO2(x,y) ...
#define FOO3(x,y,z) ...
Run Code Online (Sandbox Code Playgroud)

我想定义一个新的宏FOO如下:

#define FOO(x,y) FOO2(x,y)
#define FOO(x,y,z) FOO3(x,y,z)
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为宏不会在参数数量上超载.

无需修改FOO2FOO3,是有一些方法来定义一个宏FOO(使用__VA_ARGS__或以其他方式),以获得分派的相同的效果FOO(x,y)FOO2,并FOO(x,y,z)FOO3

c macros c-preprocessor

168
推荐指数
6
解决办法
5万
查看次数

手动代码中存在 C++20 __VA_OPT__ 错误的类函数宏

我正在根据递归宏和 C++20 的伟大手册构建代码__VA_OPT__https://www.scs.stanford.edu/~dm/blog/va-opt.html

代码是

#include <iostream>

#define PARENS ()

// Rescan macro tokens 256 times
#define EXPAND(arg) EXPAND1(EXPAND1(EXPAND1(EXPAND1(arg))))
#define EXPAND1(arg) EXPAND2(EXPAND2(EXPAND2(EXPAND2(arg))))
#define EXPAND2(arg) EXPAND3(EXPAND3(EXPAND3(EXPAND3(arg))))
#define EXPAND3(arg) EXPAND4(EXPAND4(EXPAND4(EXPAND4(arg))))
#define EXPAND4(arg) arg

#define FOR_EACH(macro, ...)                                    \
  __VA_OPT__(EXPAND(FOR_EACH_HELPER(macro, __VA_ARGS__)))
#define FOR_EACH_HELPER(macro, a1, ...)                         \
  macro(a1)                                                     \
  __VA_OPT__(FOR_EACH_AGAIN PARENS (macro, __VA_ARGS__))
#define FOR_EACH_AGAIN() FOR_EACH_HELPER

#define ENUM_CASE(name) case name: return #name;

#define MAKE_ENUM(type, ...)                    \
enum type {                                     \
  __VA_ARGS__                                   \
};                                              \
constexpr const char *                          \
to_cstring(type _e)                             \
{ …
Run Code Online (Sandbox Code Playgroud)

c++ g++ c++20

3
推荐指数
1
解决办法
1788
查看次数

标签 统计

c ×1

c++ ×1

c++20 ×1

c-preprocessor ×1

g++ ×1

macros ×1