c++ - 当条件为真时,有什么方法可以连接宏参数?
问题描述
当条件为真时,我想连接宏参数:
#define concat(x, y) (x##y)
#define concat_if(cond, x, y) (((cond) > 0) ? concat(x, y) : (x))
例如,
int concat_if(1, hello, 0); //int hello0;
int concat_if(0, hello, 1); //int hello;
但这会产生编译错误(Clang):
error: use of undeclared identifier 'hello0'
int concat_if(1, hello, 0);
^ note: expanded from macro 'concat_if'
#define concat_if(cond, x, y) (((cond) > 0) ? concat(x, y) : (x))
^ note: expanded from macro 'concat'
#define concat(x, y) (x##y)
^
<scratch space>:303:1: note: expanded from here
hello0
^
error: use of undeclared identifier 'hello'
int concat_if(1, hello, 0);
^
2 errors generated.
解决方案
#include <boost/preprocessor.hpp>
#define concat_if(cond, x, y) BOOST_PP_IF(cond, BOOST_PP_CAT(x, y), (x))
int concat_if(1, hello, 0); //int hello0;
int concat_if(0, hello, 1); //int (hello);
从头开始,很容易模仿 Boost 的功能:
#define concat(x, y) concat_i(x, y)
#define concat_i(x, y) x##y
#define concat_if(cond, x, y) concat(concat_if_, cond)(x, y)
#define concat_if_0(x, y) (x)
#define concat_if_1(x, y) concat(x, y)
int concat_if(1, hello, 0); //int hello0;
int concat_if(0, hello, 1); //int (hello);
条件附加到辅助宏前缀,并为任一结果定义单独的宏。请注意,我建议将所有这些宏设为 FULL_UPPERCASE。
推荐阅读
- vba - .Write objHTTP.responseBody 运行时错误 3001
- json - JSON.Lua json.encode 返回 nil
- node.js - 有人可以告诉我为什么我在 chrome 控制台中收到此错误:(
- java - Java中的SQL注入攻击
- json - 将“漂亮打印”的 JSON 字符串转换为紧凑格式表示的最简单方法是什么?
- c++ - 在 CentOS 7.5 上安装 RMARIADB
- python - TypeError:“MIMEText”对象不可调用
- ios - swift:单元格中的图像
- spring-boot - 使用 Feign 和 Spring MVC 时对 ResponseEntity 进行编码和解码?
- python - 在 django 模型中,我想对列值列表进行表查找,以用作我的一个字段中的选择。可能吗?