
From: "Electric Monk" <yg-boost-users@m.gmane.org>
"Terje Slettebø" <tslettebo@chello.no> wrote in message news:031b01c2fc98$f1065db0$8d6c6f50@pc...
However, one can still simply overload/specialise the lexical_cast
function
template, to get the same effect, even though this is not documented. It's similar to being able to specialise components in the standard library. I think this is a simpler way of doing it than the earlier way.
For example:
#include <boost/lexical_cast.hpp>
namespace boost { template<> double lexical_cast<double>(const std::string &source) { // ... } }
This barfs under my compiler (BCB4/Win32), since you can't specialize a function template.
The compiler is right, but for a different reason. I hadn't tested the above code, and the reason it doesn't work is that the primary template looks like this: template<class Target, class Source> Target lexical_cast(Source arg) Since it takes the source by value, it can't be specialised to take it by const reference. The reason it takes it by value rather than const reference, is that using const reference gives problems with std::numeric_limits used in the implementation. Therefore, it has to be done e.g. like this: namespace boost { template<> double lexical_cast<double>(std::string source) { // ... } } Some compilers may have problems deducing the second template parameter, in which case you may specify it explicitly: template<> double lexical_cast<double, std::string>(std::string source) You can specialise a function template, as long as it's a total specialisation, like the above. What you can't do is to partially specialise a function template, although there exists a formal proposal to change that. I wrote in the earlier posting that you could overload/specialise it. However, as the target type is not deduced, the only option is specialising it.
From what little investigation I've done so far, it seems that the best place to do this specialization is in the boost::detail::lexical_stream class, such as the specialization already done for extracting a std::string from the lexical_stream.
You could do it there, but in this case you'd have to specialise the whole class, with all the member functions. Regards, Terje