Boost logo

Boost :

Subject: Re: [boost] Formal Review Request: Boost.String.Convert
From: Emil Dotchevski (emildotchevski_at_[hidden])
Date: 2009-02-18 16:36:33


On Wed, Feb 18, 2009 at 1:03 PM, Andrey Semashev
<andrey.semashev_at_[hidden]> wrote:
> Emil Dotchevski wrote:
>
>> What I had in mind is that foo could implement to_string or to_wstring
>> or both, and the library would supply generic overloads of
>> to_string/to_wstring that would kick-in as needed. So, if I give you:
>>
>> std::string to_string( foo const & );
>>
>> then after you include foo.hpp and presumably boost/to_string.hpp, you can
>> say
>>
>> foo x;
>> std::wstring s=to_wstring(x);
>>
>> which would bind to boost::to_wstring (since there isn't a foo
>> overload of to_wstring) which would do the conversion using the foo
>> to_string overload.
>
> Hmm... No, that doesn't look very useful either. My common practice of
> operator<< definition is to define it as a template on the character type,
> like this:
>
> struct foo
> {
> template< typename CharT, typename TraitsT >
> friend std::basic_ostream< CharT, TraitsT >&
> operator<< (
> std::basic_ostream< CharT, TraitsT >& strm,
> foo const& x);
> };
>
> This allows to find the operator via ADL and have the common implementation
> for any character type under the same name (operator<< in this case).
>
> I would expect the same level of flexibility from the proposed library. Even
> more, I'd like it to use the operators if they are already defined for the
> class.

You can still do this with what I am proposing. When someone does

foo x;
std::string s=to_string(x);

this would bind to the foo to_string overload if available, if not it
would bind to the foo/ostream overload of << if available, etc. The
idea is to automatically pick the best conversion available to produce
the string the caller needs.

This makes the to_string library implementation more complex, but the
benefit is that it is possible to define simple, non-template
to_string overloads for various types. The reason I like that is
because I don't have to put to_string implementations in headers.

Also, it makes it very easy to integrate 3rd party types into the
framework. Suppose you have something like:

class bar
{
public:
  std::string getstr() const;
private:
  ...
};

and you want to integrate it into the to_string framework. All you
have to do is (presumably you can't alter bar itself):

std::string to_string( bar const & x ) { return x.getstr(); }

(note, no coupling between the above to_string overload and the
to_string library) and now you can do:

bar x;
std::wstring s=to_wstring(x); //the library handles string->wstring
conversion automatically.

Emil Dotchevski
Reverge Studios, Inc.
http://www.revergestudios.com/reblog/index.php?n=ReCode


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