Boost logo

Boost :

From: Rob Stewart (stewart_at_[hidden])
Date: 2005-03-30 11:07:08


From: Vladimir Prus <ghost_at_[hidden]>
>
> While it's generally considered a bad practice to provide implicit
> conversions, I think it would be good to provide such a conversion for the
> boost::format class. Currently, I can't write:
>
> string s;
> s = format("%1%") % 10;
>
> and need to write
>
> s = (format("%1%") % 10).str();
>
> Maybe it's specifics of my code, but I can count 10 such conversions in a
> single source file. I think that:
>
> 1. Calling .str() is rather inconvenient.
> 2. The 'format' class most often used inside expressions. It's not likely to
> be passed around to functions and so the dangers of implicit conversions are
> not critical.

While your usage might be proven normative and thus could be used
to justify adding an implicit conversion, how about another
approach? Why not add a non-member function str() or
to_string():

template <class T>
std::string
boost::str(T const & source_i)
{
   return source_i.str();
}

Then, you example becomes:

   s = str(format("%1%") % 10);

(I don't even know the types involved in your expression to make
a non-templated function. Besides, I thought this might be
generally useful.)

To generalize further (warning: uncompiled, untested code):

template <class T>
typename boost::result_of<&T::str()>::type
boost::str(T const & source_i)
{
   return source_i.str();
}

That would be more flexible. This could also be the primary
template specialization and it could be specialized for other
types that don't provide a str() member function.

-- 
Rob Stewart                           stewart_at_[hidden]
Software Engineer                     http://www.sig.com
Susquehanna International Group, LLP  using std::disclaimer;

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