C++ 促进预验证相等性测试

C++ Boost preprosessor equality testing

本文关键字:测试 验证 C++      更新时间:2023-10-16

Boost PP 的相等性测试看起来像

# define NOT_EQUAL_I(x, y) CAT(NOT_EQUAL_CHECK_, NOT_EQUAL_ ## x(0, NOT_EQUAL_ ## y))
# define NOT_EQUAL_CHECK_NIL 1
# define NOT_EQUAL_CHECK_NOT_EQUAL_0(c, y) 0
# define NOT_EQUAL_CHECK_NOT_EQUAL_1(c, y) 0
# define NOT_EQUAL_CHECK_NOT_EQUAL_2(c, y) 0
# define NOT_EQUAL_CHECK_NOT_EQUAL_3(c, y) 0
# define NOT_EQUAL_0(c, y) IIF(c, NIL, y(1, NIL))
# define NOT_EQUAL_1(c, y) IIF(c, NIL, y(1, NIL))
# define NOT_EQUAL_2(c, y) IIF(c, NIL, y(1, NIL))
# define NOT_EQUAL_3(c, y) IIF(c, NIL, y(1, NIL))

这依赖于宏在这种情况下扩展一次的事实。

然而,另一种解决方案很容易想到,而且成本似乎更低(空间):

#define EQ_0_0 ,
#define EQ_1_1 ,
#define EQ_2_2 ,
#define EQ_3_3 ,
#define SECOND(_,x,...) x
#define PARSE(...) __VA_ARGS__
#define EQ(x,y) PARSE(SECOND PARSE() (0 EQ_##x##_##y 1, 0 ))

那么为什么Boost选择前一种形式而不是后一种形式呢?它们有什么好处和坏处?

提升考虑不允许...的环境(BOOST_PP_VARIADICS)。