Boost logo

Boost :

From: Terje Slettebø (tslettebo_at_[hidden])
Date: 2002-07-23 20:41:13

>From: "Rene Rivera" <grafik666_at_[hidden]>

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

>>>From: "Gennaro Prota" <gennaro_prota_at_[hidden]>
>>> 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
>>without extra parameters.

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

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

Yes, you may default it, like here. However, if you want to use it, you need
to supply it as an extra parameter. It has also been experimented with
storing the stream statically, so it wouldn't have to to passed as a
parameter. However, that would mean it wouldn't be thread-safe, and there
could be problems with reenterancy.

By the way, the above isn't legal code. If you dereference a null-pointer,
you end up in the land of undefined behaviour... I see that David Abrahams
point this out in another posting, too.

>>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 :-)

Sure, you can do that. But lexical_cast is meant to be a generic cast, so it
may be applied to any type that has stream operators. A solution with
sprintf/sscanf or swprintf/swscanf will only be able to handle the types you
write it to handle. If you want to extend it to handle more types, you have
to change the code. You don't have to do that with lexical_cast. Also, using
streams means it also uses the currently set locale, to handle the
formatting. This is something that the C functions won't do.

Why wouldn't you want to use streams? Efficiency? In that case, have you
measured the difference? Bjarne Stroustrup did some measurements with
various implementations, comparing C I/O with streams, and found that
sometimes, the stream version was faster, and sometimes, the C I/O version
was faster. So clearly, it's possible to write a stream implementation that
is as least as fast as the C I/O version.



Boost list run by bdawes at, gregod at, cpdaniel at, john at