libboxes
boxes is a set of specialised containers built on top of STL
simple_lru_example.cpp
#include <boxes/cache.hpp>
#include <functional>
#include <iostream>
uint64_t fib(uint64_t n) {
if (n <= 1) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
int main() {
auto make_fib_cache = [](std::size_t cacheSize) {
return [cacheSize](uint64_t n) -> uint64_t {
auto cache = boxes::cache::makeLRU<uint64_t, uint64_t>(cacheSize);
auto impl = [cache = std::move(cache)](auto &self,
uint64_t n) mutable -> uint64_t {
if (cache.contains(n)) {
return cache.at(n);
}
uint64_t result = 0;
if (n <= 1) {
result = n;
} else {
result = self(self, n - 1) + self(self, n - 2);
}
cache.insert(n, result);
return result;
};
return impl(impl, n);
};
};
auto fib_cache = make_fib_cache(32);
std::cout << "Fibonacci with cache of 50: " << fib_cache(50) << std::endl;
// This will take a long time... and memory
// std::cout << "Fibonacci of 50: " << fib(50) << std::endl;
return 0;
}
Implements generic cache with pluggable eviction policies.