Boost logo

Boost :

From: Rene Rivera (grafik666_at_[hidden])
Date: 2002-07-23 14:18:29


[2002-07-23] Terje Slettebø wrote:

>>From: "Gennaro Prota" <gennaro_prota_at_[hidden]>
>
>Apparently, I haven't got Craig's posting (yet), so I reply to it as well,
>here.
>
>> On Mon, 22 Jul 2002 21:44:45 +0100, "Craig Henderson"
>> <cdm.henderson_at_[hidden]> wrote:
>> > However, I have managed to solve the problem
>> >with the introduction of a second template function, as shown below.
>
>> template<typename Target, typename Source, typename E>
>> inline Target lexical_cast(Source arg, E& interpreter)
>> {
>> //E interpreter;
>> Target result;
>>
>> if(!(interpreter << arg) || !(interpreter >> result) ||
>> !(interpreter >> std::ws).eof())
>> throw bad_lexical_cast();
>>
>> return result;
>> }
>
>Adding a second parameter, such as this, has been suggested earlier, too (I
>had it in an earlier suggestion of lexical_cast), but has been rejected,
>from what I understand from Kevlin, as is explained in "Future directions"
>above here.
>
>> The main disadvantage is that in the general case you have to pass an
>> instance of the interpreter type. The main advantage (?) is that you
>> are not limited to default construct it so, theoretically, you could
>> pass some sort of "special interpreter".
>
>That was my idea, too, so that you could customize the interpreter, e.g.
>setting formatting, etc. However, I understand the interest in keeping this
>without extra parameters.

There's a trick I use to get rid of the need for "extra" template parameters
that might be usefull here...

template<typename Target, typename Source, typename E>
inline Target lexical_cast(Source arg, E& interpreter =
    (*reinterpret_cast<E*>(0))
    ...

It might be usefull if having an custom interpreter is really needed.
Although it might require pertial templates in this case.

>And with the new version, you can do this:
>
>lexical_cast< std::basic_string<wchar_t> >(123);
>
>:)
>
>Internally, it uses specialisations, based on the source and target types,
>to select character type for the interpreter. You may even use other
>character types than char or wchar_t.

I wrote the equivalent but with swprintf/swscanf because I didn't want to
use streams :-)

-- grafik - Don't Assume Anything
-- rrivera_at_[hidden] - grafik_at_[hidden]
-- 102708583_at_icq - Grafik666_at_AIM - Grafik_at_[hidden]


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