Boost logo

Boost :

Subject: [boost] [lexical_cast] A suggestion
From: Vladimir Batov (batov_at_[hidden])
Date: 2009-01-13 07:26:04


I use boost::lexical_cast quite a bit. Possibly due to specifics of my task I constantly stumble upon two things:

1. It throws if/when conversion fails;
2. It requires the 'Target' class to be default-constructible.

I'd like to suggest extending the existing
 
    template<class Target, class Source>
    Target
    lexical_cast(Source const& arg)

interface with

    template<class Target, class Source>
    Target
    lexical_cast(Source const& arg, Target const& failure_value)

The behavior of the latter would be to return the 'failure_value' if/when the conversion fails. That communicates the fact of the conversion failure differently (without an exception thrown), i.e. its usage would be as following:

    int value = boost::lexical_cast(some-string, -1);
    if (value == -1) conversion failed.

In fact, my usage pattern is such that I often do not even need to check the success of the conversion -- if the conversion fails, the supplied failure/default value is returned/used and proceeded with.

Secondly, the proposed lexical_cast requirements would be looser -- no need for the default-constructibility of the Target, only the copy-constructibility (as already required anyway). For that the current lexical_cast implementation

    if(interpreter << arg) {
        Target result;
        if (interpreter >> result)
            return result;
    }
    throw_exception(bad_lexical_cast(typeid(Source), typeid(Target)));
    return Target(); // normally never reached (throw_exception)

would change (for the proposed interface) to something like

    if(interpreter << arg) {
        Target result(failure_value);
        if (interpreter >> result)
            return result;
    }
    return failure_value;

I am not sure how much value such an interface extension might have for others but for my usage pattern the benefit would be quite visible as the majority of our classes are with no default constructors and handling conversion-failure exceptions is quite a hassle... not to mention that for whatever guided/misguided reasons exceptions are virtually banned for our mission-critical development.

Best,
V.


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