Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

Compile time min/max calculation

Synopsis
Usage
Example
Demonstration Program
Rationale
Credits

The class templates in <boost/integer/static_min_max.hpp> provide a compile-time evaluation of the minimum or maximum of two integers. These facilities are useful for generic programming problems.

namespace boost
{

typedef implementation-defined static_min_max_signed_type;
typedef implementation-defined static_min_max_unsigned_type;

template <static_min_max_signed_type Value1, static_min_max_signed_type Value2 >
    struct static_signed_min;

template <static_min_max_signed_type Value1, static_min_max_signed_type Value2>
    struct static_signed_max;

template <static_min_max_unsigned_type Value1, static_min_max_unsigned_type Value2>
    struct static_unsigned_min;

template <static_min_max_unsigned_type Value1, static_min_max_unsigned_type Value2>
    struct static_unsigned_max;

}

The four class templates provide the combinations for finding the minimum or maximum of two signed or unsigned (long) parameters, Value1 and Value2, at compile-time. Each template has a single static data member, value, which is set to the respective minimum or maximum of the template's parameters.

#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' should be 429 or { 9, 2, 4, 0 }
    //...
}

The program static_min_max_test.cpp is a simplistic demonstration of various comparisons using the compile-time extrema class templates.

Sometimes the minimum or maximum of several values needs to be found for later compile-time processing, e.g. for a bound for another class template.

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


PrevUpHomeNext