c++ - 当条件为真时,有什么方法可以连接宏参数吗?

标签 c++ 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.

最佳答案

With Boost.PP :

#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);

From scratch ,很容易模拟 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。

关于c++ - 当条件为真时,有什么方法可以连接宏参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55623892/

相关文章:

c++ - 我的转置矩阵代码有什么问题?

c++ - 在 Mac 上构建 iotivity

c - 在 C 中,有没有一种方法可以使用单个格式化的打印语句打印未知大小的数组?

c++ - C++中的虚函数问题

c++ - 将结构体转换为整数合法吗?

c - 为什么数组有调用约定?

c - realloc() 一个递增的指针

c - 如何使用 fscanf 读取带有分隔符的文件?

c - 关于交叉编译的 c 中内置函数的警告

c++ - 不可行函数模板的类型推导