Last active
December 25, 2021 13:49
-
-
Save hackeris/9df1876cef071b2d9fdf867cd61d9b3f to your computer and use it in GitHub Desktop.
C++ memorize function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <map> | |
#include <functional> | |
#include <iostream> | |
template<typename R, typename... Args> | |
auto memorize(std::function<R(Args...)> &&f) { | |
using Func = std::function<R(Args...)>; | |
struct memory { | |
explicit memory(std::function<R(Args...)> &&f) : _f(f) {} | |
auto operator()(Args &&... args) { | |
auto iter = _mem.find(std::make_tuple(args...)); | |
if (iter != _mem.end()) { | |
return iter->second; | |
} else { | |
auto ret = _f(args...); | |
_mem.template emplace(std::make_tuple(args...), ret); | |
return ret; | |
} | |
} | |
Func _f; | |
std::map<std::tuple<Args...>, R> _mem; | |
}; | |
return memory(std::forward<Func>(f)); | |
} | |
template<typename Callable> | |
auto memorize(Callable &&f) { | |
return memorize(std::function(std::forward<Callable>(f))); | |
} | |
int add(int a, int b) { | |
std::cout << "add(" << a << "," << b << ")" << std::endl; | |
return a + b; | |
} | |
int main() { | |
auto m_add = memorize(add); | |
auto r1 = m_add(1, 2); | |
auto r2 = m_add(1, 2); | |
std::cout << "r1: " << r1 << ", r2: " << r2 << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment