|
Boost : |
From: Thorsten Ottosen (nesotto_at_[hidden])
Date: 2003-01-15 08:50:17
Hi Boosters,
I was wondering if it would be possible to implement a wrapper around
built-in types to provide automatic detection of conversion
problems:
template< typename T >
class safe_numeric : boost::operators< safe_numeric<T> >
{
public:
typedef boost::detail::fixed_numeric_limits<T> result_traits;
safe_numeric() : t_( T() )
{
}
template< typename S >
safe_numeric( S s ) : t_( boost::numeric_cast<T>( s ) )
{
}
template< typename S >
safe_numeric& operator=( S s )
{
t_ = boost::numeric_cast<T>( s );
return *this;
}
operator T() const
{
return t_;
}
private:
T t_;
};
namespace boost
{
namespace detail
{
template <class T>
struct fixed_numeric_limits< safe_numeric<T> > :
public std::numeric_limits< T >
{
static const bool is_specialized = true;
};
}
}
typedef safe_numeric<char> Char;
typedef safe_numeric<short> Short;
typedef safe_numeric<int> Int;
typedef safe_numeric<long> Long;
typedef safe_numeric<float> Float;
typedef safe_numeric<double> Double;
Now, the most interesting question is if it's possible to get complete
transparency for the clients perspektive. I guess it's
a matter of overloading operators appropriately. Any comments on the
usefullness of such a template?
regards
Thorsten Ottosen
-- Thorsten Ottosen, Aalborg University nesotto_at_[hidden] --------------------------------------------------- C++: my_map[key]++; Java: if ( !my_map.containsKey( key ) ) my_map.put( key, new Integer( 1 ) ); else { Integer count = ( Integer )my_map.get( key ) ); int icount = count.IntValue(); my_map.put( key, new Integer( ++icount ) ); }
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk