Boost logo

Boost :

From: Martin Adrian (adrianm_at_[hidden])
Date: 2006-04-15 10:32:09


Reece Dunn <msclrhd <at> hotmail.com> 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());
}

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

template <typename CharT>
bool istream_failed(myistream<CharT>& is) {
  if (is.fail()) return true;
  if (is.eof()) return false;
  if ((is.flags() & std::ios_base::skipws) == 0) return true;
  is >> std::ws; // remove trailing whitespace
  return !is.eof(); // ok if eof
}

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;
}

>
> 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.

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


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk