title: How do I return from a function inside a lambda?
body: <p>Consider the following toy code to determine whether a range contains an element:</p>
  
  <pre><code>template&lt;typename Iter, typename T&gt;
  bool contains1(Iter begin, Iter end, const T&amp; x)
  {
      for (; begin != end; ++begin)
      {
          if (*begin == x) return true;
      }
      return false;
  }
  </code></pre>
  
  <p>(Yes I know, there are already perfectly fine algorithms in the standard library, that's not the point.)</p>
  
  <p>How would I write the same thing with <code>for_each</code> and a lambda? The following doesn't work...</p>
  
  <pre><code>template&lt;typename Iter, typename T&gt;
  bool contains2(Iter begin, Iter end, const T&amp; x)
  {
      std::for_each(begin, end, [&amp;x](const T&amp; y) {
          if (x == y) return true;
      });
      return false;
  }
  </code></pre>
  
  <p>...because that would only return from the lambda, not from the function.</p>
  
  <p>Do I have to throw an exception to get out of the lambda? Again, there are probably a dozen better solutions to this specific problem that do not involve lambdas at all, but that's not what I'm asking for.</p>