Boost logo

Boost :

From: Reece Dunn (msclrhd_at_[hidden])
Date: 2006-04-15 20:08:20

Martin Adrian wrote:
> Reece Dunn <msclrhd <at>> writes:
> > What about converting to different string types, mainly std::string or
> std::wstring?
> I use to_string and to_wstring but both actually comes from basic_to_string
> which is templated on StringT.
> In my own stream class I have implemented c_str() so basic_to_string looks
> something like:
> template <typename StringT, typename T>
> StringT basic_to_string(call_traits<T>::arg_type x) {
> myostream<StringT::char_type> os;
> os << x;
> return StringT(os.c_str());
> }

What if StringT doesn't have a char_type define (such as const wchar_t *)?
What if you have something like basic_string< char, case_insensitive< char > >? Or define a different allocator?

You could have:

   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;
   return StringT( os.str().c_str());

> template <typename T>
> std::string to_string(const T& x) { return basic_to_string<std::string, T>
> (x); }

That is similar to what I initially came up with.

> template <typename T, typename SequenceT>
> T from_string(const SequenceT& seq) {
> T v;
> myistream<SequenceT::value_type> is(begin(seq), end(seq));
> is >> v;
> if (istream_failed(is)) throw invalid_argument("from_string");
> return v;
> }

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.

> > I am also working on implementing to_string and string_to :). Maybe we could
> combine our efforts and get
> > to_string/string_to into Boost.
> Sure. I can send you my code.


> > At the moment, my versions don't have locale support and string_to isn't
> returning optional<T>
> I no fan of optional and prefer throw/default. I have not seen a situation
> where optional would be easier to use but many where it would be more
> difficult.

I haven't looked into using optional as I am not familiar with the library. Therefore, I am not qualified to answer questions regarding its usefulness in this situation :).

> locale support is a must for me since I want to use to_string both for user
> messages (which uses global locale) and SQL statements (which uses classic + a
> special date facet).

Yeah. Others have requested this for lexical_cast. I was planning on adding versions which take a locale as a second parameter, but haven't gotten around to it yet.

- Reece
Express yourself instantly with MSN Messenger! Download today it's FREE!

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