【问题标题】:How to resolve the return type of a forwarding reference?如何解析转发引用的返回类型?
【发布时间】:2021-12-25 11:41:45
【问题描述】:

有一个现有的expected<T,E> 类提供这些typedefsoperators

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&&

现在我正在编写这样的函数:

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

我应该在评论区放什么?
我试过auto&amp;&amp;*e,它收到了excepted&amp;&amp;,但返回了value_type&amp;
我也试过std::forward,但还是编译不出来。

我该怎么办?

【问题讨论】:

  • 我喜欢这个概念!我做了一堆可以“解包”指针或 throw、unique_ptr 或 throw、可选或 throw、共享指针或 throw……这很有趣! (显然是结果或错误expected 的变体,其意图也是如此。)
  • @Eljay 您还可以添加一个名为exceptionFactory 的参数,代码如下:return e.has_value() ? *std::forward&lt;E&gt;(e) : throw exceptionFactory(e.error());

标签: c++ templates forward-reference


【解决方案1】:

你可以使用decltype(auto)作为返回类型:

#include <utility>

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

【讨论】:

    猜你喜欢
    • 2013-01-20
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2018-10-21
    • 2021-03-12
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    相关资源
    最近更新 更多