Boost logo

Boost :

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


Hi, all

Recently I have used lexical_cast extensively. And I found it
disapointing that I can't make it more effitient in some particular
cases where it could be very simple. The only thing that I need is a
bit flexibility of lexical_cast implementation. So I end up with the
following implementation:

template<class Stream, class Source>
static void default_upload_impl( Stream& interpreter, Source const&
arg )
{
    if( !(interpreter << arg) )
        throw bad_lexical_cast();
}

template<class Stream, class Target>
static void default_unload_impl( Stream& interpreter, Target& result )
{
    if( !(interpreter >> result) ||
        !(interpreter >> std::ws).eof())
        throw bad_lexical_cast();
}

template<class Source>
struct lexical_cast_interpreter {
    explicit lexical_cast_interpreter( Source const& ){}

    void upload( Source const& arg ) {
default_upload_impl( m_interpreter, arg ); }

    template<class Target>
    void unload( Target& result ) {
default_unload_impl( m_interpreter, result ); }

private:
    string_stream m_interpreter;
};

} // namespace detail

template<class Target,class Source>
Target lexical_cast(Source const& arg)
{
    detail::lexical_cast_interpreter<Source> interpreter( arg );

    interpreter.upload( arg );

    Target result;

    interpreter.unload( result );

    return result;
}

} // namespace boost

Now to speed up a lexical_cast from std::string I am able to write a
specialization:

namespae detail {

template<>
struct lexical_cast_interpreter<std::string> {
    explicit lexical_cast_interpreter( std::string const&
arg )
    : m_interpreter( arg.data(), arg.size() ) {}

    void upload( std::string const& ) {}

    template<class Target>
    void unload( Target& result ) {
default_unload_impl( m_interpreter, result ); }

private:
    in_string_stream m_interpreter;
};

} // namespace detail

Code and small performance comparison program is located here:

http://groups.yahoo.com/group/boost/files/lexical_cast_propositions/pr
oposition1.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