咨询C++标准库是否存在缓存函数上次返回值的工具
咨询C++标准库是否存在缓存函数上次返回值的工具
你好!针对你的问题,目前C++标准库中并没有直接提供缓存函数上次返回值的工具。不过你提到的cache_last适配器确实是C++ Ranges库的规划内容,但它尚未成为标准库的正式组成部分。
你描述的使用场景非常典型:在使用标准算法(比如std::find_if)时,频繁以相同参数调用耗时函数(比如字符串比较、从映射容器取值这类操作),会产生不必要的性能损耗,缓存上次调用的结果确实是个高效的解决方案。
如果要在现有C++代码中实现这个功能,你需要自己编写类似的缓存包装器,你给出的CacheLast实现思路是完全可行的。下面是你的完整示例代码:
#include <functional> #include <iostream> #include <vector> template <typename Fn, typename I, typename O> class CacheLast { private: bool initialized = false; I last_arg = {}; O last_res = {}; std::function<Fn> fn; public: CacheLast(Fn arg_fn) : fn(arg_fn) {} const O& operator()(const I& arg) { if (initialized && arg == last_arg) { return last_res; } initialized = true; last_arg = arg; return last_res = fn(arg); } }; // Some function which could take time to calculate size_t function(const std::string& s) { return s.length(); } int main() { auto ruler = CacheLast<decltype(function), std::string, size_t>(function); std::cout << ruler("First") << "\n"; std::cout << ruler("Second") << "\n"; std::cout << ruler("Second") << "\n"; // This is already taken from cache }
这里给你一个小优化建议:可以修改模板参数让编译器自动推导类型,这样创建CacheLast对象时不用手动指定模板参数,代码会更简洁。调整后的模板类示例如下:
template <typename Fn> class CacheLast { private: using ArgType = typename std::function<Fn>::argument_type; using ReturnType = typename std::function<Fn>::result_type; bool initialized = false; ArgType last_arg = {}; ReturnType last_res = {}; std::function<Fn> fn; public: CacheLast(Fn arg_fn) : fn(arg_fn) {} const ReturnType& operator()(const ArgType& arg) { if (initialized && arg == last_arg) { return last_res; } initialized = true; last_arg = arg; return last_res = fn(arg); } }; // 此时创建对象只需: auto ruler = CacheLast(function);
备注:内容来源于stack exchange,提问作者Damir Tenishev
相关产品推荐
相关产品推荐

