当条件为真时,有没有办法连接宏参数
Is there any way to concatenate macro arguments when condition is true?
我想在条件为真时连接宏参数:
#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);
从头开始,很容易模仿 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所有这些宏。
如果你只是预处理
int main()
{
int concat_if(1, hello, 0); //int hello0;
int concat_if(0, hello, 1); //int hello;
}
你得到
int main()
{
int (((1) > 0) ? (hello0) : (hello));
int (((0) > 0) ? (hello1) : (hello));
}
如您所见,编译器必须处理所有这些令牌。这些行在语法上是无效的,因为条件表达式是表达式。需要可评估。
换句话说,使用条件运算符声明不同名称的变量不是一个可行的策略。
我无法提出任何建议来解决您的问题,因为我不明白真正的问题是什么。此刻感觉像是XY问题。
相关文章:
- Qt5:连接:如果插槽的参数少于信号,如何使用"连接"
- Wt 连接函数,将参数传递给作为连接函数参数的函数
- 文档在哪里说明如果参数不是从末端删除参数,则无法从QT信号插槽连接中删除参数?
- 使用libpq组织PostgreSQL数据库连接参数
- 如何使用分隔符连接命令行参数
- 当条件为真时,有没有办法连接宏参数
- Qt - 使用λ函数修改先前连接信号的插槽参数
- 使用"const char*"和"char*"参数连接两个第三方模块
- 在参数包中获取函数指针的返回类型,并将其保存为与其他参数连接的元组
- 无法为 QT 连接函数提供参数
- 在可变参数模板函数中连接字符串(和数字)
- Qt用参数将QAction连接到函数
- C++连接函数错误-参数无效
- C++ 将两个字符 * 连接到命令行参数的 LPTSTR
- 为连接的OMNeT++门分配随机选择但匹配的参数
- 正在将QAxObject事件与IDispatch*类型的参数连接
- 将返回对象的信号连接到没有参数的插槽
- 通过将模板参数与字符串连接起来生成C++类型名
- sprintf 连接参数: sprintf ( a+b, " " )
- 获取连接参数