Boost logo

Boost :

Subject: Re: [boost] function convert() -- do you find it useful?
From: Andrzej Krzemienski (akrzemi1_at_[hidden])
Date: 2014-06-29 02:01:35


2014-06-28 23:52 GMT+02:00 Krzysztof Czainski <1czajnik_at_[hidden]>:

> 2014-06-28 22:58 GMT+02:00 Andrzej Krzemienski <akrzemi1_at_[hidden]>:
>
> > Hi,
> > This is the second time that I have found the following function useful
> > when playing with variants of Optional library:
> >
> > template <typename T, typename U>
> > typename std::enable_if<std::is_convertible<U, T>::value, T>::type
> > convert(U && u)
> > { return std::forward<U>(u); }
> >
> > It performs an implicit conversion from U to T, but you can call it
> > explicitly.
> >
>
> +1
>
> I even have such a function in my tools, and use it often.
>
> I chose a shorter name "as", because since this only forces an implicit
> conversion, I find verbosity unwanted here.
>
> Consider preventing dangerous uses like this (not tested):
> auto& x = convert<T const&>( U() );
>
> You can prevent that by adding a static_assert in this function:
> // Prevent returning an lvalue reference to a temporary
> BOOST_STATIC_ASSERT( !is_lvalue_reference<T>::value ||
> is_reference<U>::value );
>
> BTW, why not get rid of the enable_if< is_convertible > part? Won't a
> message "U isn't convertible to T" pointing into the function be more
> readable, than a message "There's no 'convert' function"?
>

If I remove enable_if, my second use cans will stop working -- because the
semantics of convert() are no longer visible to sfinae.

Regards,
&rzej


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