在C ++ 11中编写通用memoization函数 [英] Writing Universal memoization function in C++11
问题描述
寻找一种方法来实现一个通用的通用memoization函数,它将采用一个函数并返回相同的记忆版本?
Looking for a way to implement a universal generic memoization function which will take a function and return the memoized version of the same?
寻找类似@memo来自Norving的网站)在python中的装饰器。
Looking for something like @memo (from Norving's site)decorator in python.
def memo(f):
table = {}
def fmemo(*args):
if args not in table:
table[args] = f(*args)
return table[args]
fmemo.memo = table
return fmemo
在C ++中表达通用和可重用的装饰器,可能使用C ++ 11的新特性?
Going more general, is there a way to express generic and reusable decorators in C++, possibly using the new features of C++11?
推荐答案
:
template <typename R, typename... Args>
std::function<R (Args...)> memo(R (*fn)(Args...)) {
std::map<std::tuple<Args...>, R> table;
return [fn, table](Args... args) mutable -> R {
auto argt = std::make_tuple(args...);
auto memoized = table.find(argt);
if(memoized == table.end()) {
auto result = fn(args...);
table[argt] = result;
return result;
} else {
return memoized->second;
}
};
}
在C ++ 14中,可以使用广义返回类型通过返回 std :: function
强加的额外间接。
In C++14, one can use generalized return type deduction to avoid the extra indirection imposed by returning std::function
.
他们在 std :: function
首先留给读者做练习。
Making this fully general, permitting passing arbitrary function objects without wrapping them in std::function
first is left as an exercise for the reader.
这篇关于在C ++ 11中编写通用memoization函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!