跨平臺C++整數類型 之一 固定寬度整數(boost和C++11)

原來一直使用ACE的跨平臺整數類型,比如:ACE_UINT32, 但是自己使用C++的風格是明顯的現代風格,以範型爲主,所以最近開始逐步替換ACE的代碼,改用boost庫。

在boost庫中,standard integer types用來支持跨平臺的整數類型,我用的是1.48版本,參考文檔:

http://www.boost.org/doc/libs/1_48_0/libs/integer/doc/html/boost_integer/cstdint.html

boost庫的整數實現基於99 C標準,不選98C++標準爲基礎是因爲有些情況下的未定義行爲。將來新的C++標準如果規定了跨平臺整數類型的話,boost的這個庫可能被廢除。不過現在C++11還沒有編譯器完全支持,也沒有太多選擇。

自己實現固然可以,不過意味着分發困難和很多測試,看明白boost如何實現的就可以了。沒必要自己幹這脹活吧。

注意,總是使用boost::開頭的類型和模板,不要直接使用boost引入的C的標準類型和宏。

現在開始。

boost提供了精確寬度的整數類型,採用int#_t 命名,#就是位數,比如int8_t 代表有符號的8位整數。那麼它的真實對應物是什麼?

注意,我這裏是Ubuntu 64bit, GCC4.6.3, boost 1.48.0


[cpp] view plaincopyprint?

  1. /* For GCC 2.7 and later, we can use specific type-size attributes.  */  

  2. # define __intN_t(N, MODE) \  

  3.   typedef int int##N##_t __attribute__ ((__mode__ (MODE)))  

  4. # define __u_intN_t(N, MODE) \  

  5.   typedef unsigned int u_int##N##_t __attribute__ ((__mode__ (MODE)))  

  6.   

  7. # ifndef __int8_t_defined  

  8. #  define __int8_t_defined  

  9. __intN_t (8, __QI__);  

  10. __intN_t (16, __HI__);  

  11. __intN_t (32, __SI__);  

  12. __intN_t (64, __DI__);  

  13. # endif  



用宏替換後,其實就是:


[cpp] view plaincopyprint?

  1. typedef int int8_t __attribute__ ((__mode__ (__QI__)))  

用到了幾個GCC編譯器的指令


__attribute__, __mode和 __QI__


##是宏的連接符號。


這篇帖子解釋了這些指令:http://stackoverflow.com/questions/4559025/what-does-gcc-attribute-modexx-actually-do

__QI__就代表最小尋址單元,一個字節,8位。

__HI__ 以及後面的指令都是8位的若干倍數。


至於無符號固定寬度整數類型,前面加上u,形如:uint#_t 就是無符號整數的固定寬度表達方法。

實現採用了另一套typedef,沒有用上面的編譯器指令


[cpp] view plaincopyprint?

  1. /* Unsigned.  */  

  2. typedef unsigned char       uint8_t;  

  3. typedef unsigned short int  uint16_t;  

  4. #ifndef __uint32_t_defined  

  5. typedef unsigned int        uint32_t;  

  6. # define __uint32_t_defined  

  7. #endif  

  8. #if __WORDSIZE == 64  

  9. typedef unsigned long int   uint64_t;  

  10. #else  

  11. __extension__  

  12. typedef unsigned long long int  uint64_t;  

  13. #endif  


更新:2013/9/14

不過今天開始啓用C++11,現在有了標準的可用。參考文檔:

http://en.cppreference.com/w/cpp/types/integer

幾乎和boost裏面的一樣。所以本文標題也有所改變。


本文轉自 http://blog.csdn.net/csfreebird/article/details/8223166 

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