预处理元编程笔记(生肉)

BOOL(x) 怎么做?
目标:0->0, 其他 -> 1.
方法:
#define BOOL(x) BOOL_ ## x
此时,
#define BOOL_0 0
#define BOOL_1 1
#define BOOL_2 2

#if(condition, t, f) => if(bool(condition), t, f) => if_1(t, f) t, if_0(t, f) f

注意这个:https://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html
gcc 和 MSVC 支持。其他编译器普遍不支持

分治:

#define MACRO_GET_1(str, i)
(sizeof(str) > (i) ? str[(i)] : 0)

#define MACRO_GET_4(str, i)
MACRO_GET_1(str, i+0),
MACRO_GET_1(str, i+1),
MACRO_GET_1(str, i+2),
MACRO_GET_1(str, i+3)

#define MACRO_GET_16(str, i)
MACRO_GET_4(str, i+0),
MACRO_GET_4(str, i+4),
MACRO_GET_4(str, i+8),
MACRO_GET_4(str, i+12)

#define MACRO_GET_64(str, i)
MACRO_GET_16(str, i+0),
MACRO_GET_16(str, i+16),
MACRO_GET_16(str, i+32),
MACRO_GET_16(str, i+48)

#define MACRO_GET_STR(str) MACRO_GET_64(str, 0), 0 //guard for longer strings

using seq = sequence<MACRO_GET_STR(“Hello world!”)>;
二分展开。用在循环上。另见 BOOST_PP_WHILE。用到循环的地方基本都用这个方法展开 token

Leave a Reply

Your email address will not be published. Required fields are marked *