Home > OS >  How to resolve the return type of a forwarding reference?
How to resolve the return type of a forwarding reference?

Time:12-26

There is an existing expected<T,E> class which provides these typedefs and operators:

value_type = T
operator *(): expected<T,E>& -> value_type&
              const expected<T,E>& -> const value_type&
              expected<T,E>&& -> value_type&&
              const expected<T,E>&& -> const value_type&&

Now I'm writing a function like this:

template <typename E> 
/*type*/ Unwrap(E&& e)
{
    return e.has_value() ? /*what*/
        : throw e.error();
}

what should I put in the comment block?
I've tried auto&& and *e, it received an excepted&& but returned a value_type&.
I've also tried std::forward, but it even couldn't be compiled.

how should I do?

CodePudding user response:

You can use decltype(auto) as the return type:

#include <utility>

template<typename E> 
decltype(auto) Unwrap(E&& e) {
  return e.has_value() ? *std::forward<E>(e)
    : throw e.error();
}
  • Related