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"
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章