-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemoize.h
33 lines (23 loc) · 823 Bytes
/
memoize.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// memoize - add chashing to pure function
// Part of lvvlib - https://github.com/lvv/lvvlib
// Copyright (c) 2000-2013
// Leonid Volnitsky (Leonid@Volnitsky.com)
// from http://slackito.com/2011/03/17/automatic-memoization-in-cplusplus0x/
#ifndef LVV_MEMOIZE_H
#define LVV_MEMOIZE_H
#include <functional>
#include <map>
namespace lvv {
template <typename ReturnType, typename... Args>
std::function<ReturnType (Args...)>
memoize (std::function<ReturnType (Args...)> func) {
std::map<std::tuple<Args...>, ReturnType> cache;
return ([=](Args... args) mutable {
std::tuple<Args...> t(args...);
if (cache.find(t) == cache.end())
cache[t] = func(args...);
return cache[t];
});
}
}; // namespace lvv
#endif // LVV_MOMOIZE_H