Boost logo

Boost :

Subject: Re: [boost] Formal Review Request: Boost.Convert
From: Andrew Troschinetz (ast_at_[hidden])
Date: 2009-02-19 15:57:20


It seems like there's still a lot of discussion going on about the
interface even when Vladimir is plodding on, so I thought I might
offer another candidate that I haven't seen put forth just yet.

  template<class Target, class Source>
  *unspecified-type* convert_to(const Source& value);

This would give us the flexibility to easily implement an interface
that could be used like so:

  int i = convert_to<int>("5").get(); // get "5" converted to int
(throw on error)

  unsigned u = convert_to<unsigned>("-1").get_or(0); // get "-1"
converted to unsigned or else 0

  int i = convert_to<int>("0xff").get_special(as_hex()); // get "0xff"
converted to int using as_hex functor

And we could easily add another function to support STL algorithm
composition while maintaining consistency in our public interface.

  template<class Target, class Source>
  *unspecified-type* convert_to();

Which could be used like this:

  vector<string> strs;
  strs.push_back("1"); strs.push_back("2"); strs.push_back("3");
  vector<int> ints;
  transform (strs.begin (), strs.end(), back_inserter (ints),
convert_to<int, string>().get()); // throw on error

  vector<string> strs;
  strs.push_back("1"); strs.push_back("-2"); strs.push_back("3");
  vector<unsigned> uints;
  transform (strs.begin (), strs.end(), back_inserter (uints),
convert_to<unsigned, string>().get_or(0)); // default to 0

  vector<string> strs;
  strs.push_back("0xa"); strs.push_back("0xb"); strs.push_back("0xc");
  vector<int> ints;
  transform (strs.begin (), strs.end(), back_inserter (ints),
convert_to<unsigned, string>().get_special(as_hex())); // as hexadecimal

With this approach, the template argument is still required even in
the defaulting-to-fallback form, making the interface more consistent.
It is also much clearer and explicit what kind of behavior you want
the conversion to exhibit. For example through the use of get() that
you risk throwing an exception, with get_or() you get a default on
error, or with get_special() you can use whatever special formatting
conversion you feel like providing. The interface on the unspecified-
type could be easily extended later, through the addition of new
methods. And it's easy to return a different type when convert_to() is
called without any parameter that could work intuitively with STL
algorithms and maintain a consistent interface.

--
Andrew Troschinetz
Applied Research Laboratories

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