【发布时间】:2018-12-05 23:29:33
【问题描述】:
当相关对象可能不存在时,有哪些方法可以创建用于从索引自定义容器中检索对象的 API?
到目前为止,我想到了:
-
抛出异常
T get(int index) const { if(not_exists(index)) throw std::out_of_range("Index is out of range"); return get_base(index); } -
构造 T 并返回它
T get(int index) const { if(not_exists(index)) return T{}; return get_base(index); } -
返回 bool 并作为参考检索
bool get(int index, T & obj) const { if(not_exists(index)) return false; obj = get_base(index); return true; } -
如果找不到则使用默认参数
T get(int index, T def_obj) const { if(not_exists(index)) return def_obj; return get_base(index); } -
结合 4 + 2
T get(int index, T def_obj = {}) const { if(not_exists(index)) return def_obj; return get_base(index); } -
修改容器以添加此类对象(警告 -
get将不再是const!)T get(int index, T def_obj = {}) { if(not_exists(index)) set(index, def_obj); return get_base(index); }
每种解决方案的优缺点是什么?我错过了什么吗?
我特别担心在高并发环境中进行推理,我希望为客户端提供尽可能直观和安全的 API。
【问题讨论】:
-
boost::optional 应该是个不错的选择。
-
@seccpur:为什么不
std::optional? -
这两种解决方案都不是万能的。出于这个原因,许多 API 提供了多种选项。以标准库为例,这就是为什么你有
container::find、container::at和container::operator[] -
@seccpur 你能把这个作为答案发布吗? :)
标签: c++ containers api-design