Im需要一个对象,该对象可以用map包装try_emplace的延迟初始化(实际上只在需要时调用工厂类型的函数),以便在try_emplace中转换ok
std::map<std::string, bool> cache_;
cache_.try_emplace("hello", lazy_wrapper([]{return true;}));或者也许
std::map<std::string, whatever_wrapper<bool> > cache_;
cache_.try_emplace("hello", []{return true;});我认为这应该是可能的,但主要是寻找现成的解决方案。( std / boost)与滚动我自己的包装器相比。
发布于 2020-06-25 14:43:52
您最终将不得不自己实现“尝试-嵌入”逻辑,因为没有简单的函数来实现它。
template<typename Map, typename Key, typename Func>
auto lazy_try_emplace(Map &map, const Key &key, Func f)
{
auto it = map.find(key);
if(it == map.end())
return map.emplace(key, f());
return std::pair(it, false);
}是的,这会两次查找元素,但如果不实际成为std::map实现的一部分,就无法避免这种情况(这就是try_emplace存在的原因)。搜索时间可以通过将map.find替换为map.lower_bound、更改条件测试以查看键是否与key不相等以及与迭代器一起使用emplace_hint来最小化。
发布于 2020-06-25 14:36:35
你真的需要包装吗?你可以这样做:
// C++20
if (!cache_.contains("hello"))
cache_.emplace("hello", [] { return true; });
// pre C++20
if (cache_.count("hello") == 0)
cache_.emplace("hello", [] { return true; });简单,清晰,没有头痛。
https://stackoverflow.com/questions/62577415
复制相似问题