二進制對數模板<boost/integer/static_log2.hpp> 中的類模板用於確定一個給定值中最高位的位置。該工具可用於解決泛型編程的問題。
namespace boost
{
typedef implementation-defined static_log2_argument_type;
typedef implementation-defined static_log2_result_type;
template < static_log2_argument_type arg >
struct static_log2
{
static const static_log2_result_type value = implementation-defined;
};
template < >
struct static_log2< 0 >
{
// 零的對數無定義
};
} // namespace boost
boost::static_log2 類模板帶一個模板參數,類型為 static_log2_argument_type 的值。該模板只定義了一個成員 value, 它給出了模板參數的冪2對數向下取整後的值。
由於零對於任何基數的對數都是無定義的,所以 static_log2 有一個模板參數為零的特化。該特化版沒有成員,因此試圖使用零的對數將引發一個編譯期錯誤。
註:
static_log2_argument_type 是一個 無符號整數類型 (C++ 標準,3.9.1p3).static_log2_result_type 是一個 整數類型 (C++ 標準,3.9.1p7).
#include "boost/integer/static_log2.hpp"
template < boost::static_log2_argument_type value >
bool is_it_what()
{
typedef boost::static_log2<value> lb_type;
int temp = lb_type::value;
//...
return (temp % 2) != 0;
}
//...
int main()
{
bool temp = is_it_what<2000>();
//...
# if 0
temp = is_it_what<0>(); // 將給出一個錯誤
# endif
//...
temp = is_it_what<24>();
//...
}
程序 static_log2_test.cpp 簡單地示範了對多個二進制對數類模板例子的實例化結果。
底數為二的(二進制)對數函數,縮寫為 lb, 有時候被用於給出計算機算法的階數估算(order-estimates)。向下取整後的對數可被視為一個值中的最高的2的冪,對應於該值的最高一個被置位的位(對於二進制整數)。有時這個最高位元的位置可以用於泛型編程,它要求該位置是靜態(即 在編譯期)可用的。
boost::static_log2
的參數類型和結果類型現在是 typedef 的。以前,它們分別被硬編碼為 unsigned long 和 int. 請在新代碼中使用所提供的 typedefs (並盡可能更新舊的代碼)。
The original version of the Boost binary logarithm class template was written by Daryle Walker and then enhanced by Giovanni Bajo with support for compilers without partial template specialization. The current version was suggested, together with a reference implementation, by Vesa Karvonen. Gennaro Prota wrote the actual source file.
Revised July 19, 2004
© Copyright Daryle Walker 2001.
© Copyright Gennaro Prota 2004.