
What if StringT doesn't have a char_type define (such as const wchar_t *)?
(char_type should be value_type, which is part of the basic_string standard) How do you expect to_string to work with "const wchar_t*"? returning a pointer to a static buffer, dymaicly allocating it? In my class implementation I have a to_c_str() function which returns a pointer to the streams internal buffer. string_conversion<std::string> conv(somelocale, &std::hex); conv.to_string(123); //returns std::string conv.to_c_str(123); // returns const char*
What if you have something like basic_string< char, case_insensitive< char > ? Or define a different allocator?
Don't understand the question. basic_to_string should work fine with any string class that can be constructed from a "StringT::value_type*".
typedef typename traits::char_type< StringT >::type char_type; typedef typename traits::char_traits< StringT >::type char_traits; typedef typename traits::allocator_type< StringT >::type allocator; std::basic_ostringstream< char_type, char_traits, allocator > os; os << x;
What does the string's traits and allocator got to do with the stream? Is it so that just beacuse I use a pool allocator for my strings I automaticly want to use it for streams as well? It should probably be template <typename StringT, typename TraitsT, typename AllocatorT, typename T> StringT to_string(const T& x) { std::basic_ostringstream< StringT::value_type, TraitsT, AllocatorT > os; os << x; return StringT(os.str().c_str()); } but since you can't have default template parameters for functions it complicates usage a lot without adding much value. (My stream class also uses small string optimization so allocation rarly happens).
People in this discussion have expressed a dislike of throwing exceptions on conversion failure w.r.t. lexical_cast. We could have a string_to and try_string_to, where the try_ version returns T and throws, while the other returns optional<T> and doesn't throw.
My version allows you to specify what should be returned on error instead. try_string_to can then easily be implemented as: template <typename T, typename StringT> T try_string_to(const StringT& str) { return string_to<T, StringT>(str, T()); }