【发布时间】:2021-01-22 06:32:29
【问题描述】:
如何在 C++11 中重写以下代码以使用 boost::optional 或 boost::none?
std::unique_ptr<FooBase> find( std::string key)
{
std::map<std::string, std::function<std::unique_ptr<FooBase>(void)> > m{
{"key1", [](){return std::make_unique<BarDerived>();} },
{"key2", [](){return std::make_unique<BarDerived1>();} } };
auto it = m.find(key);
if (it != std::end(m))
return (it->second());
else
return nullptr;
}
【问题讨论】:
-
我不确定是否将智能指针包装到
optional中。std::unique_ptr已经有一个null-state,所以你基本上会加倍。想象一下:if (foo && *foo)是必需的,以确保可选项有一个值并且包装的智能指针是活动的...... -
make_unique 不是 c++11 顺便说一句
-
也许这answer 有帮助
-
您也可以考虑完全不使用 std::function,切换到 unordered_map 并且如果您能够使用 c++17 切换到 string_view :godbolt.org/z/xEvG5P 比较所有 3 个版本的 disassmbly自己看看
-
@Yamahari 在 C++17 之前你已经可以使用 boost::string_ref 或 boost::string_view
标签: c++ c++11 boost-optional stdoptional