【发布时间】:2014-04-30 18:26:37
【问题描述】:
我正在学习如何使用 C++ lambda 函数以及 <functional> 的 function 类。我正在尝试解决这个Code Golf 作为练习(挑战是晚餐咖喱)
我有这个功能:
// This creates a function that runs y a number of
// times equal to x's return value.
function<void()> Curry(function<int()> x, function<void()> y)
{
return [&]() {
for (int i = 0; i < x(); i++)
{
y();
}
};
}
为了测试这一点,我在 main() 中有这段代码:
auto x = [](){ return 8; };
auto y = [](){ cout << "test "; };
auto g = Curry(x, y);
这会在 Functional.h 中抛出 Access violation reading location 0xCCCCCCCC.。
然而,当我将 lambda 函数从 Curry() 内部复制粘贴到我的 main 内部时,如下所示:
auto x = [](){ return 8; };
auto y = [](){ cout << "test "; };
auto g = [&]() {
for (int i = 0; i < x(); i++)
{
y();
}
};
我让代码按预期运行。为什么会这样?
【问题讨论】:
-
懒得回答其他人了,不过here's Curry for Dinner in C++14:
auto Curry=[](auto x,auto y){return[=]{for(auto i=x();i--;y());};};