Boost logo

Boost :

From: Don Waugaman (dpw_at_[hidden])
Date: 2000-06-06 12:47:39


>
> > > > Returning default values on failure is ambiguous, unless you
> > > > know from your context that the default would be impossible.
> > >
> > > Agreed. But sometimes we may indeed know this:
> > >
> > > int n = stream_cast<int>(argv[1], 0);
> > > if (n < 5)
> > > {
> > > std::cerr << "x must be a number greater than 4.";
> > > return EXIT_FAILURE;
> > > }
> > >
> > > Do we care whether the user typed "fred" or "3"? Possibly not.
> >
> > This type of error handling scenario is a poster child for exceptions.
> > The exception overhead is insignificant, and it makes easy generic and
> > more robust error handling. True, you don't need to tell to the user
> > that the parameter wasn't even a number, but sometimes it can be nice.
> > With exceptions, you can use the same code, or at least the same
> > coding pattern, for problems that do and do not have the luxury of
> > knowing that 0 (or whatever) is illegal and for problems that do and
> > do not need verbose error reporting.
>
> The point is that the programmer should make the decision whether a default
> return value or an exception is more appropriate.
>
> When faced with an exception-throwing stream_cast, I would be forced to
> define my own
>
> template<class T, class S> T stream_cast_def(S const & source, T const &
> defaultValue = T())
> {
> try
> {
> return stream_cast<T>(source);
> }
> catch(stream_cast_exception const &)
> {
> return defaultValue;
> }
> }
>
> which is, in this case, inefficient.

Could we accomodate both approaches from the same interface? I'm
thinking here of having a stream_cast(std::nothrow) option, somewhat
like how the new operator works.

template<typename Target, typename Source>
        inline Target stream_cast(Source arg, std::nothrow_t &)

This would allow use of the throwing stream_cast without qualification,
and allow the programmer to select the non-throwing stream_cast when
appropriate. It uses a familiar mechanism to differentiate between
the two alternatives.

Thoughts?

-- 
    - Don Waugaman (dpw_at_[hidden])    O-             _|_  Will pun
Web Page: http://www.cs.arizona.edu/people/dpw/            |   for food
In the Sonoran Desert, where we say: "It's a dry heat..."  |     <><
All generalizations are false.

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