Boost logo

Boost :

From: Alessandro Molina (javanx_at_[hidden])
Date: 2003-05-27 18:25:34


Hi, I'm new to this list and I'm writing here just to suggest to you a different
implementation for lexical_cast.
Actually lexical_cast doesn't make easy to add possibilities for new casts, and
for example if I have to cast from
IpAddress class to an int it wouldn't be easy. (even casting IpAddress to
std::string obbligates me to overload << operator)

Having to write something to do that I've ended up with writing something like
lexical_cast but which really easy to expand for casting anything to anything
else.

This is the function which will perform the semantic_cast and as you can see it
simply calls a SemanticCastActuator, so writing new SemanticCastActuators we
will be able to cast also our own defined types.

template < class TargetT, class SourceT >
TargetT semantic_cast(const SourceT &orig) throw(std::bad_cast)
{
        try {
                return SemanticCastActuator<TargetT, SourceT>()(orig);
        }
        catch(...) {
                throw;
        }
}

For example here there are the SemanticCastActuators which does what
lexical_cast currently does (without any error checking code)

//General SemanticCastActuator for unknown casts (this will just raise a
bad_cast exception)
template < class TargetT, class SourceT >
struct SemanticCastActuator
{
        TargetT operator()(const SourceT &source) throw(std::bad_cast)
        {
                throw std::bad_cast();
        }
};

//SemanticCastActuator to cast from something to a std::string
template < class SourceT >
struct SemanticCastActuator<std::string, SourceT>
{
        std::string operator()(const SourceT &source) throw(std::bad_cast)
        {
                std::ostringstream ss;
                ss << source;
                return ss.str();
        }
};

//SemanticCastActuator to cast from a std::string to something else
template < class TargetT >
struct SemanticCastActuator<TargetT, std::string>
{
        TargetT operator()(const std::string &source) throw(std::bad_cast)
        {
                TargetT retv;
                std::istringstream ss(source);
                
                ss >> retv;
                return retv;
        }
};

Tell me what do you think about this, maybe there is a good and fast way to just
expand lexical_cast without having to change it and I didn't see it :)

Alessandro Molina


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