c++ - boost::optional deprecated get_value_or

标签 c++ rvalue-reference boost-optional

我怀疑 boost::optional 的 get_value_or 已被弃用,因为如果将右值作为 default 参数传递是不安全的。但是,有时能够引用可选值或默认替代值很有用。

以下安全吗?

template<typename T>
T const& get_reference_or(boost::optional<T> const& opt, T const& alt)
{
    if (opt) return opt.get();
    else return alt;
}

template<typename T>
T const& get_reference_or(boost::optional<T> const&, T&&) = delete;

最佳答案

如所写,您的代码在类型推导方面存在问题,因为 T 可从两个参数推导出来。但是假设你实际上使 T 只能从可选的中推导出来:

template <class T>
struct NonDeducedHelper { using type = T; };

template <class T>
using NonDeduced = typename NonDeducedHelper<T>::type;

template<typename T>
T const& get_reference_or(boost::optional<T> const& opt, NonDeduced<T> const& alt)
{
    if (opt) return opt.get();
    else return alt;
}

template<typename T>
T const& get_reference_or(boost::optional<T> const&, NonDeduced<T>&&) = delete;

然后,代码几乎是安全的,因为当一个非 const 右值被用作 get_reference_or 的默认值时,它将尝试使用已删除的重载并失败编译。但是,为了 100% 安全,您还应该删除 const 右值的重载:

template<typename T>
T const& get_reference_or(boost::optional<T> const&, NonDeduced<T> const&&) = delete;

关于c++ - boost::optional deprecated get_value_or,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49872570/

相关文章:

c++ - 用另一个 bool 值 boost 可选

c++ - boost::optional 不允许我重新分配 const 值类型

c++ - 如何在 node.js 中使用用 c++ 编写的函数

c++ - 有没有一种更简单的方法来获取包裹在智能指针中的类的成员?

c++ - 使用 std::move 函数签名传递 vector

C++11 构造函数参数:std::move 和值或 std::forward 和右值引用

c++ - 在 Google 测试框架的测试用例中访问 argc 和 argv 的方法是什么?

c++ - 旋转播放器模型以指向一个点

c++ - C++ 实现是否允许假定任何右值引用函数参数是唯一的?

c++ - 在 Android Studio 中进行原生调试时查看 boost::optional 内容