編譯期整數類型的界限C++ 標準庫的 <limits> 頭文件提供了一個類模板 numeric_limits<>,它對每種基本類型進行了特化。
對於整數類型,要關注的 std::numeric_limits<> 成員有:
static const bool is_specialized; // 對於整數為 true對於多數應用為說,這些已經足夠了。但是對於 min() 和 max() 就有問題,因為它們不是常量表達式(std::5.19),還有一些應用也需要常量表達式。
static T min() throw();
static T max() throw();
static const int digits; // 對於整數,# value bits
static const int digits10;
static const bool is_signed;
static const bool is_integer; // 對於整數為 true
類模板 integer_traits 解決了這個問題。
integer_traits.hpp 摘要namespace boost {
template<class T>
class integer_traits : public std::numeric_limits<T>
{
static const bool is_integral = false;
};
// 對於所有整數類型進行特化
}
integer_traits 派生自
std::numeric_limits. 對於主模板,它增加了單個
bool 成員 is_integral,具有編譯期常量值 false. 不過,對於所有整數類型 T (std::3.9.1/7 [basic.fundamental]),
都提供了特化版本,定義了以下編譯期常量:
| 成員 | 類型 | 值 |
|---|---|---|
is_integral |
bool | true |
const_min |
T |
等於 std::numeric_limits<T>::min() |
const_max |
T |
等於 std::numeric_limits<T>::max() |
注意:這裡提供了一個標誌 is_integral, 因為雖然用戶自定義的整數類會特化
std::numeric_limits<>::is_integer = true,
但是對於用戶自定義類,編譯期常量 const_min 和
const_max 仍然是沒有提供的。
程序 integer_traits_test.cpp
檢驗了 integer_traits 類。
c Copyright Beman Dawes 2000
Distributed under the Boost Software License, Version 1.0. See www.boost.org/LICENSE_1_0.txt