【发布时间】:2022-12-02 21:49:35
【问题描述】:
年轻的 c++ 开发人员,我对项目的网络缓存很感兴趣。这几天我一直在尝试实现一个网络缓存,通过学习文章和教程,我写了一个没有库的原型。我的问题真的是我发现了 Boost 库。我正在尝试在我的网络缓存中实现它。专门实现这个:
https://www.boost.org/doc/libs/1_66_0/libs/multi_index/doc/examples.html#example9 "这个数据结构是用 multi_index_container 通过组合一个序列索引和一个 hashed_unique 类型的索引来实现的。"
目前我的课程看起来像这样,通过单元测试,它可以工作,但我的目标是尽可能精确地实施有问题的 lib Boost,尤其是多索引容器。
我试图改变项目的类型但它没有用,就像这样:
typedef multi_index_container<items,indexed_by<sequenced<>,hashed_unique<identity<Item> >>> item_list;
我收到一条消息:非静态数据成员“_items”的使用无效。这种错误我能理解,但我没有指定它,因为它是让我担心的全局实现
如果你发现除了我的精确问题之外还有其他错误,我也是一个接受者。
template<typename Tkey, typename Tval>
class CacheWeb{
private:
unsigned int capacity;
std::list<std::pair<Tkey, Tval>> items;
std::unordered_map<key, typename std::list<std::pair<Tkey, Tval>>::iterator> lookup;
CacheWeb(const CacheWeb&) = delete;
CacheWeb& operator=(const CacheWeb&) = delete;
int capacityOut(){
if( capacity == 0 || lookup.size() < capacity ) {
return 0;
}
int cnt = 0;
while(lookup.size() > capacity) {
lookup.erase(items.back().first);
items.pop_back();
++cnt;
}
return cnt;
};
public:
CacheWeb(int icapacity) : capacity(icapacity){};
virtual ~CacheWeb() = default;
int size(){
return lookup.size();
};
bool empty(){
return lookup.empty();
};
void clear(){
lookup.clear();
items.clear();
};
bool contains(const Tkey& key){
return lookup.find(key) != lookup.end();
};
void remove(const Tkey& key){
auto it = lookup.find(key);
items.erase(it->second);
lookup.erase(it);
};
void put(const Tkey& key, const Tval& val){
auto it = lookup.find(key);
if( it != lookup.end() ) {
it->second->second = val;
items.splice(items.begin(), items, it->second);
return;
}
items.emplace_front(key, val);
lookup[key] = items.begin();
capacityOut();
};
std::list<std::pair<Tkey, Tval>>getItems(){
return items;
};
const VAL_T& get(const Tkey& key){
const auto it = lookup.find(key);
if( it == lookup.end() ) {
throw std::invalid_argument("Key does not exist");
}
items.splice(items.begin(), items, it->second);
return it->second->second;
};
};
}
感谢您阅读我的问题,如果您有帮助,再次感谢您。
【问题讨论】:
-
请比“它不起作用”更具体是否有错误?那是什么错误?
-
我试图实现这个:typedef multi_index_container<items,indexed_by<sequenced<>,hashed_unique<identity<Item> >>> item_list;但主要是我收到一条消息:非静态数据成员“_items”的使用无效。这种错误我可以理解但我不想指定它因为它是全局实现让我担心
-
请edit 澄清问题,cmets 不支持足够的格式
-
我也编辑了! :)
-
请谈谈您运行代码时出了什么问题,以及您的期望是什么。更具体地说:对于您看到的错误尽可能准确。
标签: c++ caching serialization boost boost-multi-index