|
Boost : |
Subject: Re: [boost] [convert] no-throw and fallback feature
From: Vicente BOTET (vicente.botet_at_[hidden])
Date: 2011-05-09 17:30:27
> Message du 09/05/11 21:07
> De : "Stewart, Robert"
> A : "'boost_at_[hidden]'"
> Copie à :
> Objet : Re: [boost] [convert] no-throw and fallback feature
>
> Vicente BOTET wrote:
> > But I will first comeback to the prototype that returned a
> > pair Target,bool. As a pair is considered as a tuple we can
> > write
> >
> > tie(i,b) = convert_to(s);
>
> I thought about that briefly at one point in the discussions.
>
> > the main problem of this prototype is that target must be
> > copied and a default value is needed when the conversion fails.
>
> The extra copy is not desirable when there are reasonable (or, at least, not unreasonable) alternatives to avoid it.
I agree.
> > If we see optional as a kind of conditional tuple and we
> > imagine something like a conditional tie (let me call it
> > 'ctie'), we could be able to write
> >
> > ctie(i,b) = try_convert_to(s);
ctie will left i unchanged if b is true.
> I presume that no assignment would be done to i if b is false.
>
> That actually means writing this:
>
> int i;
> bool b;
> ctie(i, b) = try_converting_to(s);
> if (!b)
> {
> i = fallback;
> std::cerr << "using fallback\n";
> }
>
> Compare that to this:
>
> int i(fallback);
> if (!try_converting_to(s, i))
> {
> std::cerr << "using fallback\n";
> }
>
> The optional returning version provides useful benefits like no extra copy, get_value_or(), and no instance of the target type if the conversion fails.
The fist is more on the line of functional paradigm. The second on the procedural one. I understand that the procedural one can be more efficient, but the functional one separates clearly what are the in a,d the out parameters. Are both alternatives exclusive?
> > We could also write,
> >
> > if (ctie(i,b) = try_convert_to(s),b ) ....
> >
> > If in addition the result of ctie is implicitly convertible to
> > bool, we can have
> >
> > if ((ctie(i,b) = try_convert_to(s)) ...
>
> Interesting, but probably too much of a good thing.
I agree, as most of us are not used to use tie, which is really convenient in a lot of cases. tie allows to avoid the use of first and second field of a pair in a clear way. Once we are familiar with tie, ctie is less surprising to me. A better name for ctie could be opt_tie.
> Besides, the same thing is done with the following which is simpler and less tricky:
>
> int i;
> if (try_converting_to(s, i)) ...
If conversion to bool is implicit the bool parameter will be redundant and the preceding could be expressed as
int i;
if ((opt_tie(i) = try_convert_to(*int*)(s))) ...
which is not so bad.
Best,
Vicente
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk