根据https://www.boost.org/doc/libs/1_68_0/libs/preprocessor/doc/ref/seq_size.html :
BOOST_PP_SEQ_SIZE macro expands to the size of a seq.
Sample Code
#include <boost/preprocessor/seq/size.hpp> #define SEQ (a)(b)(c) BOOST_PP_SEQ_SIZE(SEQ) // expands to 3
这太神奇了。它是如何工作的?
最佳答案
您可以在此处阅读源代码:https://www.boost.org/doc/libs/1_75_0/boost/preprocessor/seq/size.hpp
针对不同的编译器有不同的版本,但差别不大。该宏的定义如下:
# define BOOST_PP_SEQ_SIZE(seq) BOOST_PP_CAT(BOOST_PP_SEQ_SIZE_, BOOST_PP_SEQ_SIZE_0 seq)
# define BOOST_PP_SEQ_SIZE_0(_) BOOST_PP_SEQ_SIZE_1
# define BOOST_PP_SEQ_SIZE_1(_) BOOST_PP_SEQ_SIZE_2
# define BOOST_PP_SEQ_SIZE_2(_) BOOST_PP_SEQ_SIZE_3
# define BOOST_PP_SEQ_SIZE_3(_) BOOST_PP_SEQ_SIZE_4
# define BOOST_PP_SEQ_SIZE_4(_) BOOST_PP_SEQ_SIZE_5
... ...
# define BOOST_PP_SEQ_SIZE_256(_) BOOST_PP_SEQ_SIZE_257
# define BOOST_PP_SEQ_SIZE_BOOST_PP_SEQ_SIZE_0 0
# define BOOST_PP_SEQ_SIZE_BOOST_PP_SEQ_SIZE_1 1
# define BOOST_PP_SEQ_SIZE_BOOST_PP_SEQ_SIZE_2 2
... ...
# define BOOST_PP_SEQ_SIZE_BOOST_PP_SEQ_SIZE_257 257
这段代码:
#define SEQ (a)(b)(c)
BOOST_PP_SEQ_SIZE(SEQ)
将扩展为:
BOOST_PP_CAT(BOOST_PP_SEQ_SIZE_, BOOST_PP_SEQ_SIZE_0 (a)(b)(c))
-> BOOST_PP_CAT(BOOST_PP_SEQ_SIZE_, BOOST_PP_SEQ_SIZE_1 (b)(c))
-> BOOST_PP_CAT(BOOST_PP_SEQ_SIZE_, BOOST_PP_SEQ_SIZE_2 (c))
-> BOOST_PP_CAT(BOOST_PP_SEQ_SIZE_, BOOST_PP_SEQ_SIZE_3)
-> BOOST_PP_SEQ_SIZE_BOOST_PP_SEQ_SIZE_3
-> 3
这就是它的工作原理。
需要注意的一点是,当序列比预期长(例如 257)时,没有准备好友好的错误消息,但是 for
中存在这种情况。 boost/preprocessor
的部分.
关于c++ - BOOST_PP_SEQ_SIZE 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65729898/