Boost logo

Boost :

Subject: [boost] function convert() -- do you find it useful?
From: Andrzej Krzemienski (akrzemi1_at_[hidden])
Date: 2014-06-28 16:58:47

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

[1st] time I needed it to implement the behavior of value_or (described in

template <class U> constexpr T optional<T>::value_or(U&& v) const&;

is_copy_constructible<T>::value is true and is_convertible<U&&, T>::value
is true.

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:

  template <typename U>
  auto value_or(U const& v) const -> decltype(convert<T>(v))
    if (*this)
      return this->value();
      return v;

  template <typename F>
  auto value_or(F const& f) const -> decltype(convert<T>(f()))
    if (*this)
      return this->value();
      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.


Boost list run by bdawes at, gregod at, cpdaniel at, john at