boost::lexical_cast string to string problem
I'm seeing a problem with lexical_cast. The following code when trying to convert from string to string fails when passed an empty string. The library code that is doing this lexical_cast does not and can not know that the input and output types are the same. I believe that this code should not throw. #include <iostream> #include <boost/lexical_cast.hpp> main() { std::string input(""); try { boost::lexical_cast<std::string>(input); } catch (boost::bad_lexical_cast& e) { std::cout << "Failed" << std::endl; } }
I'm seeing a problem with lexical_cast. The following code when
--- In Boost-Users@y..., "Jason Fischl" <yg-boost-users@m...> wrote: trying to
convert from string to string fails when passed an empty string. The library code that is doing this lexical_cast does not and can not know that the input and output types are the same.
I believe that this code should not throw.
#include <iostream> #include <boost/lexical_cast.hpp>
main() { std::string input(""); try { boost::lexical_cast<std::string>(input); } catch (boost::bad_lexical_cast& e) { std::cout << "Failed" << std::endl; } }
Since one can't partially specialise function templates, one way to do it could be that the library included something like this: namespace boost { template<> std::string lexical_cast<std::string,std::string>(std::string arg) { return arg; } template<> std::string lexical_cast<std::string,const char *>(const char *arg) { return arg; } template<> std::string lexical_cast<std::string,char *>(char *arg) { return arg; } } This is quite brittle, though, as it only works for the types given. It does work for your example, for Intel C++ and VC++, though (the compilers I've tested it with). If partial specialisation was possible, you could do: namespace boost { template<class T> T lexical_cast<T,T>(T arg) { return arg; } } Interestingly, the person behind lexical_cast, Kevlin Henney, is on the standards committee, and in this case, a language change could help his library. :) Regards, Terje
--- In Boost-Users@y..., Dave Jones <jdadson@i...> wrote:
Jason Fischl wrote:
I'm seeing a problem with lexical_cast.
What is lexical_cast<> supposed to do?
See http://www.boost.org/libs/conversion/lexical_cast.htm. Regards, Terje
participants (3)
-
Dave Jones
-
Jason Fischl
-
tslettebo1