2014-06-28 22:58 GMT+02:00 Andrzej Krzemienski <akrzemi1@gmail.com>:
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"? Regards, Kris PS. Look, how nice this looks (it even sounds English): cout << boost::as<double>(2) / 3 << endl; Compared to: cout << boost::convert<double>(2) / 3 << endl; Not to mention: cout << static_cast<double>(2) / 3 << endl; which (like Andrzej explained) brings in potentially unwanted explicit conversions.