2010-03-20 89 views
2

在二進制文件庫裏有什麼東西嗎?例如,我想寫:Boost :: binary <>

binary<10101> a; 

我很慚愧承認我試圖找到它(Google,Boost)但沒有結果。他們提到了一些有關binary_int <>但我找不到既不可用,也不能找到哪個頭文件;

感謝您的幫助。

+2

海合會您可以用' 0b10101'。 – kennytm 2010-03-20 14:33:42

+1

這樣的模板可能會導致一些大規模的代碼膨脹。 boost :: assign :: templates也會發生同樣的情況。 – 2010-03-20 14:35:30

回答

12

還有BOOST_BINARY宏。這樣使用

int array[BOOST_BINARY(1010)]; 
    // equivalent to int array[012]; (decimal 10) 

去與你的例子:

template<int N> struct binary { static int const value = N; }; 
binary<BOOST_BINARY(10101)> a; 

一旦一些編譯器支持的C++ 0x的用戶定義的文字,你可以寫

template<char... digits> 
struct conv2bin; 

template<char high, char... digits> 
struct conv2bin<high, digits...> { 
    static_assert(high == '0' || high == '1', "no bin num!"); 
    static int const value = (high - '0') * (1 << sizeof...(digits)) + 
          conv2bin<digits...>::value; 
}; 

template<char high> 
struct conv2bin<high> { 
    static_assert(high == '0' || high == '1', "no bin num!"); 
    static int const value = (high - '0'); 
}; 

template<char... digits> 
constexpr int operator "" _b() { 
    return conv2bin<digits...>::value; 
} 

int array[1010_b]; 
+2

我只是看了看源代碼 - 我想我會堅持用hex :-) – 2010-03-20 14:40:35

+0

@Neil,需要多長時間才能獲得「傳奇」徽章?我很努力,但看起來很難:) – 2010-03-20 21:26:53

+0

哦,這很容易 - 你只需要沒有什麼比你的時間更好。當然,以任何徽章爲傲都很愚蠢,但我爲銀牌「stl」徽章感到自豪,因爲它已經被授予了一些選擇的人.-) – 2010-03-20 21:51:20

相關問題