【发布时间】:2011-06-08 15:04:21
【问题描述】:
我使用 c++ 0x 已经有一段时间了,并且非常喜欢新的 Lamba 函数设施。我已经习惯于在我的 lambda 声明中指定 [=] 来表明我想将外部作用域的变量按值传递给我的 lambda。
但是,今天我遇到了一个非常奇怪的 lambda 问题。我注意到在 for_each 期间将外部范围的映射按值传递给 Lamba 的工作方式很奇怪。这是一个显示问题的示例:
void LambdaOddnessOne ()
{
map<int, wstring> str2int;
str2int.insert(make_pair(1, L"one"));
str2int.insert(make_pair(2, L"two"));
vector<int> numbers;
numbers.push_back(1);
numbers.push_back(2);
for_each ( numbers.begin(), numbers.end(), [=]( int num )
{
//Calling find() compiles and runs just fine
if (str2int.find(num) != str2int.end())
{
//This won't compile... although it will outside the lambda
str2int[num] = L"three";
//Neither will this saying "4 overloads have no legal conversion for 'this' pointer"
str2int.insert(make_pair(3, L"three"));
}
});
}
map 的许多方法都可以从 Lamba 内部调用(例如 find),但是许多其他方法在它们在 Lamba 外部编译得很好时会导致编译错误。
例如尝试使用 [ 运算符导致:
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)
尝试使用 .insert 函数导致:
error C2663: 'std::_Tree<_Traits>::insert' : 4 overloads have no legal conversion for 'this' pointer
有人理解这种不一致的行为吗?这只是MS编译器的问题吗?其他的我没试过。
【问题讨论】: