Boost logo

Boost :

From: rogeeff (rogeeff_at_[hidden])
Date: 2001-12-24 00:09:07


Hi, all

Recently I have used lexical_cast extensively. I had a requirement to
be able to accept a integer values presented with any base (10,8,16).
Also I needed to catch an input errors for unsigned integer values to
prevent negative input. With current implementation
lexical_cast<unsigned int>( "-10" ) won't catch any errors. I end up
writing small adaptor class I named integer_adaptor (I am not sure
about this name it's just proposition) with the following
functionality:

template<class IntType>
struct integer_adaptor {
    friend std::istream& operator>>( std::istream& str,
integer_adaptor& iad );
    operator IntType() { return m_value; }
private:
    IntType m_value;
};

template<class IntType>
std::istream&
operator>>( std::istream& str, integer_adaptor<IntType>& iad )
{
    str >> std::ws;
    std::istreambuf_iterator<char> it( str.rdbuf() );

    if( *it == '-' && !std::numeric_limits<IntType>::is_signed )
        throw bad_lexical_cast();

    str.flags( str.flags() | std::ios_base::basefield );

    iad.m_value = 0;

    str >> iad.m_value;

    return str;
}

I think due to a general applicability of the issue, it could worth
sharing.

Code and small test are located here:
http://groups.yahoo.com/group/boost/files/lexical_cast_propositions/pr
oposition2.cpp

Regards,

Gennadiy.


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