我能想到的最简单的例子:
std::optional<int> try_parse_int(std::string s)
{
//try to parse an int from the given string,
//and return "nothing" if you fail
}
可以使用引用参数来完成同样的事情(如下面的签名所示),但是使用std::optional
使签名和使用更好。
bool try_parse_int(std::string s, int& i);
另一种方法可以做到这一点是特别糟糕:
int* try_parse_int(std::string s); //return nullptr if fail
这需要动态内存分配,担心所有权等 - 总是更喜欢上面的其他两个签名之一。
另一个例子:
class Contact
{
std::optional<std::string> home_phone;
std::optional<std::string> work_phone;
std::optional<std::string> mobile_phone;
};
这比使用类似的东西要好得多std::unique_ptr<std::string>
对于每个电话号码!std::optional
为您提供数据局部性,这对性能非常有用。
另一个例子:
template<typename Key, typename Value>
class Lookup
{
std::optional<Value> get(Key key);
};
如果查找中没有某个键,那么我们可以简单地返回“无值”。
我可以这样使用它:
Lookup<std::string, std::string> location_lookup;
std::string location = location_lookup.get("waldo").value_or("unknown");
另一个例子:
std::vector<std::pair<std::string, double>> search(
std::string query,
std::optional<int> max_count,
std::optional<double> min_match_score);
这比拥有四个函数重载(这四个函数重载采用所有可能的组合)更有意义max_count
(或不)和min_match_score
(或不)!
It also 消除 the accursed "Pass -1
for max_count
如果您不想要限制”或“通过std::numeric_limits<double>::min()
for min_match_score
如果你不想要最低分数”!
另一个例子:
std::optional<int> find_in_string(std::string s, std::string query);
如果查询字符串不在s
,我想要“不int
" -- not无论某人决定为此目的使用什么特殊值(-1?)。
有关其他示例,您可以查看boost::optional
文档 http://www.boost.org/doc/libs/release/libs/optional/doc/html/index.html. boost::optional
and std::optional
在行为和使用方面基本上是相同的。