【发布时间】:2014-08-29 12:44:25
【问题描述】:
这是我为函数编写的通用记忆包装器。它使用tuplehash。
template<typename R, typename... Args>
class memofunc{
typedef R (*func)(Args...);
func fun_;
unordered_map<tuple<Args...>, R, tuplehash::hash<tuple<Args...> > > map_;
public:
memofunc(func fu):fun_(fu){}
R operator()(Args&&... args){
auto key = make_tuple(std::forward<Args>(args)...);
auto q = map_.find(key);
if(q == map_.end()){
R res = fun_(std::forward<Args>(args)...);
map_.insert({key,res});
return res;
}else{
return q->second;
}
}
};
斐波那契数的用法示例。
long long fibo(long long x){
static memofunc<long long, long long> memf(fibo);
// try to replace fibo with this new fibo but doesn't work, why?
// function<long long(long long)> fibo = memf;
if(x <= 2) return 1;
// this works but involves changing the original code.
// how to write code such that I dont need to manually add this code in?
return memf(x-1) + memf(x-2);
// old code
// return fibo(x-1) + fibo(x-2);
}
问题是,理想情况下,我可以在递归函数的开头添加几行并完成记忆。但是简单的替换是行不通的,这就是我卡住的地方。
【问题讨论】:
-
你有什么问题?
-
我认为OP希望在不修改memoized功能的情况下提供memoization。而且我认为递归函数是不可能的。
-
旁白:将
template<typename R, typename... Args> class memofunc{替换为template<typename Sig> class memofunc; template<typename R, typename...Args> class memofunc<R(Args)> {-- 然后将使用更改为memofunc<long long(long long)>。
标签: c++ templates c++11 recursion memoization