(E-Mail Removed) wrote:

> I need a specific non existing data type, and it seems that i am not

> smart enough to write the code my self, so if anyone will take the time

> to do it for me, they are more than welcome and i will be forever

> gratefull.

>

> Type definition:

> floating point value.

> max value == +1

> min value == -1

>

> As for precission, im afraid i dont really know how it work, but it

> would be preferable if the would be 8, 16 or 32 bit.

>

> Regards
heres something. Maybe it will help for ideas how to proceed. A fully

fledged UDT needs a full set of operations of course and ideally

details about what it does in all situations. Also needs detail

decisions on design, e.g how it interacts with other types etc.

Personally i would just live with float or double for underlying

value_type to start with

regards

Abdy Little

#include <stdexcept>

// first param is some constraint functor (see example at end)

// second is underlying value_type

template<typename Constraint,typename T>

class constrained_float{

T m_value;

public :

// check value and throw exception on out of range

static T do_constraint(T const & in)

{

Constraint f;

if( f(in)){

return in;

}

else{

throw std:

ut_of_range("constrained_float arg range");

}

}

constrained_float(T const & in)

: m_value(do_constraint(in)){}

T get() const {return m_value;}

//equals, +=, -= functions etc

constrained_float& operator =( constrained_float const & in)

{

m_value = in.get();

return *this;

}

constrained_float& operator +=( constrained_float const & in)

{

m_value = do_constraint(m_value + in.get());

return *this;

}

};

//+ - operations etc

template<typename CF,typename T>

constrained_float<CF,T> operator+(

constrained_float<CF,T> const & lhs,

constrained_float<CF,T> const & rhs

){

return constrained_float<CF,T>(

constrained_float<CF,T>::do_constraint(

lhs.get() + rhs.get()

)

);

}

// constraint policy

// restrict values to -1 <--> +1

struct constraint{

template <typename T>

bool operator()( T const & in)const

{

return ((in >= T(-1)) && (in <= T(1)));

}

};

#include <iostream>

int main()

{

typedef constrained_float<constraint,double> cfloat;

cfloat f = .999;

try{

f += 1.1; // will throw

f = 1.1; // will throw

}

catch (std::exception & e){

std::cout << e.what() <<'\n';

}

}