我打算用 C++ 编写一个记忆模式,最后采用了以下方法
std::function<int(int)> Memoize(std::function<int(int)> fn)
{
std::map<int, int> memo;
std::function<int(int)> helper = [=](int pos)
{
if (memo.count(pos) == 0)
{
memo[pos] = fn(pos);
}
return memo[pos];
};
return helper;
}
奇怪的是,我的编译器VS 2012,拒绝编译并出现以下错误
1>Source1.cpp(24): error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>' (or there is no acceptable conversion)
在我看来,编译器故意将所有内容按值捕获为 const 对象。我找不到任何对此行为的记录参考。
任何人都可以帮助我了解这里可能发生的情况吗?
Lambda 的行为或多或少类似于函数对象;像函数对象一样,它们有一个函数调用运算符,即operator()
。对于非mutable
lambdas,这个函数是const
:
[表达式.prim.lambda]
5 非泛型 lambda 表达式的闭包类型具有公共
内联函数调用运算符 [...]该函数调用运算符或
声明了运算符模板const
(9.3.1) 当且仅当
lambda 表达式的参数声明子句是没有跟随mutable
.
因为复制捕获的实体的行为就像 lambda 的成员变量一样:
15 [...] 对于复制捕获的每个实体,在闭包类型中声明一个未命名的非静态数据成员。
and non-mutable
会员cannot在a内修改const
成员函数([class.this] / 1,[dcl.type.cv] / 4),如果你想修改捕获的实体,你必须声明一个mutable
lambda.
目前你的 lambda 看起来像这样:
class Helper
{
public:
int operator()(int) const;
private:
std::map<int, int> memo;
std::function<int(int)> fn;
};
你可以想一个mutable
lambda 具有非const
operator()
,在您的情况下,lambda 可以定义如下:
std::function<int(int)> helper = [=](int pos) mutable
// etc
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)