Boost logo

Boost :

Subject: Re: [boost] [constrained] constrained_vector
From: Gordon Woodhull (gordon_at_[hidden])
Date: 2008-12-22 23:12:18


On Dec 22, 2008, at 1:47 PM, Neal Becker wrote:

> I'm interested in something like constrained, but applied to a
> vector of values. The case I'm interested in is a homogeneous
> vector of bounded int values, with bounds set at runtime.
>
> It is trivial to have a vector<bounded<int> >, but this would not be
> space efficient in the case where the policies, bounds on all the
> values are the same.

Not as general, but possible right now: use bounded with the bounds as
static members. This gives you as many classes of constraints as you
care to spell out. Example follows.

You're right though, a way to impart constraints from container to
contained would be really cool.

#include <iostream>
#include <boost/constrained_value.hpp>
#include <boost/mpl/assert.hpp>

template<typename Tag, typename T>
struct static_bound {
     operator T() const { return s_t; }
     static T s_t;
};

struct Lower {};
struct Upper {};

template<>
double static_bound<Lower, double>::s_t = -10.0;
template<>
double static_bound<Upper, double>::s_t = 10.0;

int main(int argc, char *argv[]) {
     typedef boost::constrained_value::bounded<double,
         static_bound<Lower,double>,
         static_bound<Upper,double> >::type within_10;

     // there have been reports that this will fail on msvc? worx on
gcc
     BOOST_MPL_ASSERT_RELATION( sizeof(within_10), ==, sizeof(double) );

     within_10 x;
     x = 9;
     x = -7.5;
     try {
         x = 12;
     }
     catch(std::exception const& xep) {
         std::cout << "expect except: " << xep.what() << std::endl;
     }

     return 0;
}

Cheers,
Gordon


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk