这个C ++ 11代码(memoize)是做什么的? [英] What does this C++11 code (memoize) do?

查看:209
本文介绍了这个C ++ 11代码(memoize)是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了包含此代码的文章

I found an article that contains this code:

template <typename ReturnType, typename... Args>
std::function<ReturnType (Args...)>
memoize(std::function<ReturnType (Args...)> func)
{
    std::map<std::tuple<Args...>, ReturnType> cache;
    return ([=](Args... args) mutable {
            std::tuple<Args...> t(args...);
            if (cache.find(t) == cache.end())                
                cache[t] = func(args...);
            return cache[t];
    });
}

你能解释一下吗?我不明白这里的许多事情,但最奇怪的是缓存是本地的,而不是静态的,但也许我错了,...

Can you explain this please? I can't understand many things here, but the weirdest thing is that cache is local and not static, but maybe I'm wrong and...

推荐答案

这是简单的C ++ 1x实施记忆

This is simple C++1x implementation of memoization.

memoize 函数返回关闭。返回值是一个函数,它的状态不是通过参数传递的(在这种情况下, cache 变量)。

The memoize function returns a closure. The return value is a function that has state other than what is passed through the arguments (in this case, the cache variable).

匿名函数中的 [=] 位表示返回的函数应该获取所有局部变量的副本。 cache 变量不是静态的,因为它意味着在调用返回的函数时共享。

The [=] bit in the anonymous function indicates that the returned function should take a copy of all local variables. The cache variable is not static because it is meant to be shared across invocations of the returned function.

每次调用 memoize 将返回一个与它自己的 cache 不同的函数。对 memoize 返回的特定闭包的后续调用将从 closure的缓存中插入/ fetch值

Thus, each call to memoize will return a different function with it's own cache. Subsequent calls to a specific closure returned by memoize will insert/fetch values from that closure's cache.

您可以认为这是一个稍微等同于更老的OOP版本:

You can think of this as a somewhat equivalent to the more old-school OOP version:

template <typename ReturnType, typename... Args>
class Memoize
{
    std::map<std::tuple<Args...>, ReturnType> cache;
public:
    ReturnType operator() (Args... args)
    {
        std::tuple<Args...> t(args...);
        if (cache.find(t) == cache.end())                
            cache[t] = func(args...);
        return cache[t];
    }
};

这篇关于这个C ++ 11代码(memoize)是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆