我在这个例子中使用 Boost.MultiIndex 实现了以下 LRU 实现。
问题是当我更改 index_by 部分的顺序(并相应地更新枚举 index_idx)时,我在包含以下内容的行上收到错误:
cache_.insert(ci);
通过以下诊断:
错误 1 错误 C2661: 'boost::multi_index::detail::sequenced_index::insert' : 没有重载函数需要 1 个参数 c:\code\code.cpp 79
代码如下:
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/tag.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
using namespace boost::multi_index;
template <typename Key, typename T>
class lru_cache
{
private:
struct item_t
{
Key key;
T t;
};
typedef boost::multi_index_container
<
item_t,
boost::multi_index::indexed_by
<
hashed_unique<boost::multi_index::member<item_t,Key,&item_t::key> >,
sequenced<>
>
> cache_t;
enum index_idx
{
e_map = 0,
e_seq = 1,
};
cache_t cache_;
size_t max_cache_size_;
public:
typedef typename std::pair<Key,T> item_pair_t;
lru_cache(size_t max_cache_size = 1)
: max_cache_size_(max_cache_size)
{}
bool find(const Key& key, T& t)
{
typename cache_t::nth_index<e_map>::type& hash_index = cache_.get<e_map>();
auto itr = hash_index.find(key);
if (itr != hash_index.end())
{
return false;
}
t = itr->t;
typename cache_t::nth_index<e_seq>::type& sequenced_index = cache_.get<e_seq>();
auto itr2 = cache_.project<e_seq>(itr);
sequenced_index.relocate(itr2,sequenced_index.end());
return true;
}
void insert(const Key& key, const T& t)
{
if (cache_.size() >= max_cache_size_)
{
typename cache_t::nth_index<e_seq>::type& sequenced_index = cache_.get<e_seq>();
sequenced_index.erase(sequenced_index.begin());
}
typename cache_t::nth_index<e_map>::type& hash_index = cache_.get<e_map>();
auto itr = hash_index.find(key);
item_t ci = {key,t};
if (itr == hash_index.end())
cache_.insert(ci); // <--- Error here....
else
hash_index.replace(itr,ci);
}
};
int main()
{
typedef lru_cache<int,int> lru_cache_t;
lru_cache_t lc(2);
lc.insert(1,1);
int v;
lc.find(1,v);
return 0;
}
修改后的索引排序:
typedef boost::multi_index_container
<
item_t,
boost::multi_index::indexed_by
<
sequenced<>,
hashed_unique<boost::multi_index::member<item_t,Key,&item_t::key> >
>
> cache_t;
enum index_idx
{
e_map = 1,
e_seq = 0,
};