这是一个有效的(ab)lambda表达式的使用吗? [英] Is this a valid (ab)use of lambda expressions?

查看:183
本文介绍了这是一个有效的(ab)lambda表达式的使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道, break 并不容易从一个外循环的嵌套循环中没有:

Like we all know, it's not that easy to break from a nested loop out of an outer loop without either:

  • a goto (Example code.)
  • another condition check in the outer loop (Example code.)
  • putting both loops in an extra function and returning instead of breaking (Example code.)

所有这些都有点笨拙。特别是函数版本缺少,因为缺少上下文环路被调用,因为你需要将所有你需要的循环作为参数。

此外,第二个变得更糟的每个嵌套循环。

所以,我个人仍然认为 goto 版本是最干净的。

Though, you gotta admit, all of those are kinda clumsy. Especially the function version lacks because of the missing context where the loops are called, as you'd need to pass everything you need in the loops as parameters.
Additionally, the second one gets worse for each nested loop.
So, I personally, still consider the goto version to be the cleanest.

现在,考虑所有C ++ 0x和东西,第三个选项带给我这个想法利用lambda表达式:

Now, thinking all C++0x and stuff, the third option brought me this idea utilizing lambda expressions:

#include <iostream>

bool CheckCondition(){
  return true;
}

bool CheckOtherCondition(){
  return false;
}

int main(){
  [&]{while(CheckCondition()){
    for(;;){
      if(!CheckOtherCondition())
        return;
      // do stuff...
    }
    // do stuff...
  }}();
  std::cout << "yep, broke out of it\n";
}

在Ideone的例子

这允许一个简单的 $ c>第三个选项提供,而不受上下文问题的影响,并且(几乎)像 goto 版本一样清洁。

This allows for the semantic beauty of a simple return that the third option offers while not suffering from the context problems and being (nearly) as clean as the goto version. It's also even shorter (character-wise) than any of the above options.

现在,我学会了保持我的美好的(ab)语言的使用后,我的喜悦,因为几乎总是有某种缺点。在这一个有什么吗?

Now, I've learned to keep my joy down after finding beautiful (ab)uses of the language, because there's almost always some kind of drawback. Are there any on this one? Or is there even a better approach to the problem?

推荐答案

请不要在我管理的项目中这样做。这是一个尴尬的虐待lambdas在我看来。

Please don't do that in a project I'm managing. That's an awkward abuse of lambdas in my opinion.

使用 goto 其中 goto

这篇关于这是一个有效的(ab)lambda表达式的使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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