boost.png (6897 bytes)編譯期界限模板

<boost/integer/static_min_max.hpp> 中的類模板提供了在編譯期計算兩個整數的最小或最大值的方法。在解決泛型編程的問題時,這一工具特別有用。

目錄

摘要

namespace boost
{

template < long Value1, long Value2 >
struct static_signed_min;

template < long Value1, long Value2 >
struct static_signed_max;

template < unsigned long Value1, unsigned long Value2 >
struct static_unsigned_min;

template < unsigned long Value1, unsigned long Value2 >
struct static_unsigned_max;

}

用法

以上四個類模板提供了在編譯期查找兩個有符號或無符號(long)參數的最小或最大值的方法,這兩個參數分別為 Value1Value2. 每個模板有一個靜態數據成員 value, 它分別被設置為模板參數的最小或最大值。

例子

#include <boost/integer/static_min_max.hpp>

template < unsigned long AddendSize1, unsigned long AddendSize2 >
class adder
{
public:
static unsigned long const addend1_size = AddendSize1;
static unsigned long const addend2_size = AddendSize2;
static unsigned long const sum_size = boost::static_unsigned_max<AddendSize1, AddendSize2>::value + 1;

typedef int addend1_type[ addend1_size ];
typedef int addend2_type[ addend2_size ];
typedef int sum_type[ sum_size ];

void operator ()( addend1_type const &a1, addend2_type const &a2, sum_type &s ) const;
};

//...

int main()
{
int const a1[] = { 0, 4, 3 }; // 340
int const a2[] = { 9, 8 }; // 89
int s[ 4 ];
adder<3,2> obj;

obj( a1, a2, s ); // 's' 應為 429 或 { 9, 2, 4, 0 }
//...
}

示範程序

程序 static_min_max_test.cpp 是一個簡單的示範,使用編譯器界限類模板進行了多次比較。

原理

有時需要為後續的編譯期處理,如另一個類模板的界限,而計算多個值的最小或最大值。

鳴謝

The author of the Boost compile-time extrema class templates is Daryle Walker.


Revised October 12, 2001

© Copyright Daryle Walker 2001. Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.