c++ - BOOST_PP_SEQ_SIZE 如何工作?

标签 c++ boost

根据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/

相关文章:

c++ - Windows CE 上的主板蜂鸣声

c++ - 如何在 Ubuntu 中从命令行将 Qt 控制台输出存储到文本文件中

c++ - 如何从 Objective C 调用我的 Qt/C++ Dylib?

c++ - 是否可以指定 boost::program_options 需要一个选项?

c++ - Boost Socket 在 close() 上崩溃

c++ - boost::asio 将套接字转换为安全

c++ - 如何创建 boost ssl iostream?

c++ - 可变嵌套模板类型作为参数

c++ - boost group_threads 最大并行线程数

c++ - 为什么 DirectX Device Present Hook 无法绕道工作?