#pragma once #include #include #include #include /** Простейший кэш для свободной функции. * Можете также передать статический метод класса или лямбду без захвата. * Размер неограничен. Значения не устаревают. * Для синхронизации используется mutex. * Подходит только для простейших случаев. * * Использование: * * SimpleCache func_cached; * std::cerr << func_cached(args...); */ template class SimpleCache { private: using Key = typename function_traits::arguments_decay; using Result = typename function_traits::result; std::map cache; std::mutex mutex; public: template Result operator() (Args &&... args) { { std::lock_guard lock(mutex); Key key{std::forward(args)...}; auto it = cache.find(key); if (cache.end() != it) return it->second; } /// Сами вычисления делаются не под mutex-ом. Result res = f(std::forward(args)...); { std::lock_guard lock(mutex); cache.emplace(std::forward_as_tuple(args...), res); } return res; } };