|
Boost : |
Subject: [boost] function convert() -- do you find it useful?
From: Andrzej Krzemienski (akrzemi1_at_[hidden])
Date: 2014-06-28 16:58:47
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.
[1st] time I needed it to implement the behavior of value_or (described in
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3672.html#optional.object.observe
):
template <class U> constexpr T optional<T>::value_or(U&& v) const&;
Requires:
is_copy_constructible<T>::value is true and is_convertible<U&&, T>::value
is true.
Returns:
bool(*this) ? **this : static_cast<T>(std::forward<U>(v)).
This needs to be implemented in one expression in C++11, because the
function is constexpr, so in the ternary operator, I could either apply no
cast and risk unnecessary ambiguity in result type in certain cases, or use
a static_cast and bring the explicit conversions in that I didn't want.
Function convert() saved the day.
[2nd] time was when trying to disable the overload in C++11 using SFINAE,
but I didn't want to use enable_if (see a more complete example here:
http://akrzemi1.wordpress.com/examples/overloading-enable_if-3/):
template <typename U>
auto value_or(U const& v) const -> decltype(convert<T>(v))
{
if (*this)
return this->value();
else
return v;
}
template <typename F>
auto value_or(F const& f) const -> decltype(convert<T>(f()))
{
if (*this)
return this->value();
else
return f();
}
I wanted to check with Boost developers if you find such function convert
generally useful (and worth adding somewhere in Boost), or is it just my
specific needs.
Regards,
&rzej
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk