title: C++ Fast Bitset Short-Circuit Bitwise Operations
body: <p>A demo problem: Given two <code>std::bitset&lt;N&gt;</code>s, <code>a</code> and <code>b</code> check if any bit is set in both <code>a</code> and <code>b</code>.</p>
  
  <p>There are two rather obvious solutions to this problem.  This is bad because it creates a new temporary bitset, and copies values all sorts of places just to throw them away.</p>
  
  <pre><code>template &lt;size_t N&gt;
  bool any_both_new_temp(const std::bitset&lt;N&gt;&amp; a, const std::bitset&lt;N&gt;&amp; b)
  {
      return (a &amp; b).any();
  }
  </code></pre>
  
  <p>This solution is bad because it goes one bit at a time, which is less than ideal:</p>
  
  <pre><code>template &lt;size_t N&gt;
  bool any_both_bit_by_bit(const std::bitset&lt;N&gt;&amp; a, const std::bitset&lt;N&gt;&amp; b)
  {
      for (size_t i = 0; i &lt; N; ++i)
          if (a[i] &amp;&amp; b[i])
              return true;
      return false;
  }
  </code></pre>
  
  <p>Ideally, I would be able to do something like this, where <code>block_type</code> is <code>uint32_t</code> or whatever type the <code>bitset</code> is storing:</p>
  
  <pre><code>template &lt;size_t N&gt;
  bool any_both_by_block(const std::bitset&lt;N&gt;&amp; a, const std::bitset&lt;N&gt;&amp; b)
  {
      typedef std::bitset&lt;N&gt;::block_type block_type;
      for (size_t i = 0; i &lt; a.block_count(); ++i)
          if (a.get_block(i) &amp; b.get_block(i))
              return true;
      return false;
  }
  </code></pre>
  
  <p>Is there an easy way to go about doing this?</p>