如何解决使用c ++ 11 lambdas的代码可读性
| 我真的很喜欢lambda,并且能够在C ++中使用它们是一种乐趣。但是,正如我习惯于Haskell那样,lambda确实非常适合语法,因此我在如何编写C ++而不编写难以理解的混乱长代码行的过程中苦苦挣扎。 因此,举例来说,假设我将这样写:vector<double> foo(10,0.2);
for_each(foo.begin(),foo.end(),[](double x){ std::cout << x << \" \";})
这不是很难读,lambda表达式很小。但是如果我在for_each中有一个两行或三行长的函数,这可能会成为我的问题
代码阅读技巧:
vector<double> foo(10,0.2);
randomNumberGenerator bar;
for_each(foo.begin(),[](double x){ std::cout << \"hello!\"; x+=bar()/(1+bar()); std::cout << x << \" \";})
//sorry,I couldn\'t think of a less stupid example...
这行开始变得冗长而令人讨厌,以我的口味很难读懂...
在这种情况下,您首选的代码约定是什么?我应该写:
for_each(foo.begin(),[] (double x) {
std::cout << \"hello!\"
x += bar()/(1+bar());
std::cout << x << \" \";
});
或类似的东西?我仍然认为这种语法有点不自然且难以阅读... :(
解决方法
我通常去
for_each(foo.begin(),foo.end(),[](double x) {
std::cout << \"hello!\"
x += bar()/(1+bar());
std::cout << x << \" \";
});
我已经写了几百行lambda。
,如果愿意,可以用auto
分别命名lambda:
auto const baz = [](double x)
{
std::cout << \"hello!\"
x += bar()/(1+bar());
std::cout << x << \" \";
};
std::for_each(foo.begin(),baz);
,嗯...
for_each(foo.begin(),[] (double x)
{
std::cout << \"hello!\"
x += bar()/(1+bar());
std::cout << x << \" \";
});
for (auto x : foo)
{
std::cout << \"hello!\";
x += bar()/(1+bar());
std::cout << x << \" \";
}
,我想将lambda看作只是另一个函数声明,因此,在一定范围内,请遵循与其他函数相同的约定:
// when lambdas are present,I break the enveloping method params
for_each(
foo.begin(),[] (double x)
// I also like to split the brackets,just like with any function
{
std::cout << \"hello!\"
x += bar()/(1+bar());
std::cout << x << \" \";
}); // the closing parenthesis is left with the closing bracket
,我想说的是,如果lambda的代码多于一个或两个语句,那么它应该是一个单独的命名函数。
,发布我的
std::vector<int> a;
std::find_if(a.begin(),a.end(),[&](int i)
{
return i == 0;
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。