Boost logo

Boost :

Subject: Re: [boost] [review] string convert
From: Vicente BOTET (vicente.botet_at_[hidden])
Date: 2011-05-04 20:07:08


> Message du 03/05/11 20:53
> De : "Marsh Ray"
> A : boost_at_[hidden]
> Copie à : "Jeff Flinn"
> Objet : Re: [boost] [review] string convert
>
> On 05/03/2011 11:41 AM, Jeff Flinn wrote:
> >
> > I personally don't have those reservations and the applicability of
> > Make. Even more concise with perhaps less preconceptions might be:
> >
> > as(s, 123);
>
> Just a data point: I've been using 'obj.as' as my own convention for
> a few years now and I like it.
>
> It was a little easier on a "lenient" compiler where I started using it:
>
> struct mytype
> {
> // Unimplemented general template.
> template U as() const {
> BOOST_MPL_ASSERT_MSG(false, NO_CONVERSION_TO, (U)); }
>
> // specializations define the types we support "conversions" to:
> template <> std::string as() const {return this->to_string_imp(); }
> template <> std::wstring as() const {return this->to_wstring_imp();}
> ...possibly more...
> ...
> };
>
> template
> T f()
> {
> mytype m(...);
> return m.as();
> }
>
> Just tried it again the other day with a class template on a more
> conforming compiler (which required member specializations at namespace
> scope). It was a lot more overhead code to make it work.
>
> If this library could help me define explicit conversions "as" member
> templates with a sane amount of boilerplate again, I'd be a fan.

explicit conversion are supported by C++11.

Boost.Conversion let you already define explicit conversion but not as member templates. You will need to overload the convert_to function for the Source and target types as follows:

Target convert_to(const Source& from, boost::dummy::type_tag const&)
{
// your specific code
}

Once this is done you could write your function f() as

***** Sorry I have replaced angle brackets by (* and *) **********

template (*class T*)
T f()
{
mytype m(...);
return boost::convert_to(*T*)(m);
}

Best,
Vicente


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