Boost.preprocessor

Boost.preprocessor总结

简介

在项目中发现有使用Boost库中的preprocessor库,而目前中文关于该库的介绍很少,在此根据查看Boost库的参考文档,对于该库的使用根据自己的经验进行总结。
本文主要根据Boost的官方帮助文档写的,因此如果英文阅读没有问题的读者建议,直接阅读原文,链接地址如下:
Boost官方文档

宏定义

此部分主要介绍preprocessor库中的宏定义的作用。

  1. BOOST_PP_COMMA_IF(cond)

    • 该条件判断宏根据参数cond是否为真,决定是否生成符号,;该参数的范围从0至BOOST_PP_LIMIT_MAGBOOST_PP_LIMIT_MAG表示256;
    • 当cond为0的时候,该宏拓展为空;
      具体的使用方法参考以下代码:
    #include <boost/preprocessor/punctuation/comma_if.hpp>
    #include <boost/preprocessor/repetition/repeat.hpp>
    
    #define MACRO(z, n, text) BOOST_PP_COMMA_IF(n) text
    
    BOOST_PP_REPEAT(3, MACRO, class) // expands to class, class, class
    
  2. BOOST_PP_INC(x)
    该宏表示增加x的值,增加的量为1。该宏的作用类似于C中的++运算符的功能。上限为BOOST_PP_LIMIT_MAG

    #include <boost/preprocessor/arithmetic/inc.hpp>
    
    BOOST_PP_INC(BOOST_PP_INC(6)) // expands to 8
    BOOST_PP_INC(4) // expands to 5
    
  3. BOOST_PP_REPEAT(count, macro, data)

    1. 参数count表示重复调用macro的次数,上限为BOOST_PP_LIMIT_REPEAT

    2. macro是一个三值运算宏,形式如下所示macro(z, n, data)。该宏被BOOST_PP_REPEAT调用拓展,其中z表示重复深度,n表示当前重复的序号,data表示辅助的参数,一般用于传入形参;
      关于该宏中z在宏BOOST_PP_REPEAT中无需传入参数,具体该参数的作用见后面BOOST_PP_REPEAT_z中的介绍。

    3. data一般用于传入形参。

      macro按照以下顺序进行拓展。

      macro(z, 0, data) macro(z, 1, data) ... macro(z, count - 1, data)
      

    该宏的使用见下述用例代码:

    #include <boost/preprocessor/repetition/repeat.hpp>
    
    #define DECL(z, n, text) text ## n = n;
    
    BOOST_PP_REPEAT(5, DECL, int x)  
    
    输出结果如下:
    int x0 = 0; int x1 = 1; int x2 = 2; int x3 = 3; int x4 = 4;
    
  4. BOOST_PP_REPEAT_z

  5. BOOST_PP_STRINGIZE(text)
    text转换为字符串。该预处理将运算符#字符串化以阻止其展开。该宏允许其参数先展开再对展开的结果进行字符串化。
    以下为该宏的代码用例:

    #include <boost/preprocessor/cat.hpp>
    #include <boost/preprocessor/stringize.hpp>
    
    BOOST_PP_STRINGIZE(BOOST_PP_CAT(a, b)) // expands to "ab"
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章