c++ - 使用 std::Optional 而不是自己的结构

标签 c++ c++17

我需要使用可空类型。

我找到了std::optional完全符合我的期望。

但是这个功能从 C++ 17 开始就可以使用,C++ 14 的实验分支。这意味着编译器(不同的计算机)必须更新。

它只是为数据和 bool 值分配了空间,指示变量是否存在。

为什么我应该使用这个功能而不是自己的结构?

使用 std::optional 有什么好处吗? ?

谢谢!

最佳答案

在了解您对问题的观点后,我想引用一句话来回答。

P.13: Use support libraries as appropriate.

Reason Using a well-designed, well-documented, and well-supported library saves time and effort; its quality and documentation are likely to be greater than what you could do if the majority of your time must be spent on an implementation. The cost (time, effort, money, etc.) of a library can be shared over many users. A widely used library is more likely to be kept up-to-date and ported to new systems than an individual application. Knowledge of a widely-used library can save time on other/future projects. So, if a suitable library exists for your application domain, use it.

来自 C++ Core Guidelines

关于c++ - 使用 std::Optional 而不是自己的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60169845/

相关文章:

c++ - 如何查找 USB 设备的父级是否是集线器

c++ - 在结构中初始化std::vector

c++ - Qt:强制QWebView点击一个网络元素,即使是在窗口上不可见的元素

c# - c++ std::map::find 到 c# dictionary<key,value>

c++ - for 语句中的 constexpr

C++ - 来自 std::string 的意外输出

c++ - std::invoke 不喜欢可变参数模板成员函数?

c++ - 函数指针数组的类模板参数推导适用于 clang,但不适用于 gcc

C++ - 如何让多个线程写入一个文件

c++ - 如何将 std::string 转换为 std::vector<uint8_t>?