    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Using Enum Classes as Bitfields</title>
        <link>https://members.accu.org/index.php/articles/2228</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #132 - April 2016</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c360/">o132</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-360/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+360/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Using Enum Classes as Bitfields</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 02 April 2016 21:39:18 +01:00 or Sat, 02 April 2016 21:39:18 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Scope enums have many advantages over standard enums. Anthony Williams shows how to use them as bitmasks.</p>
<p><strong>Body:</strong>&nbsp;<p>C++ 11 introduced a new feature in the form of <em>scoped enumerations</em>, also referred to as <em>enum classes</em>, since they are introduced with the double keyword <code>enum class</code> (though <code>enum struct</code> is also permissible, to identical effect). To a large extent, these are like standard enumerated types: you can declare a list of enumerators, which you may assign explicit values to, or which you may let the compiler assign values to. You can then assign these values to variables of that type. However, they have additional properties which make them ideal for use as bitfields.</p>

<h2>Key features of scoped enumerations</h2>

<p>The key features provided by scoped enumerations are:</p>

<ul>
	<li>The enumerators must always be prefixed with the type name when referred to outside the scope of the enumeration definition. e.g. for a scoped enumeration <code>colour</code> which has an enumerator <code>green</code>, this must be referred to as <code>colour::green</code> in the rest of the code. This avoids the problem of name clashes which can be common with plain enumerations.</li>
	
	<li>The underlying type of the enumeration can be specified, to allow forward declaration, and avoid surprising consequences of the compilerâ€™s choice. This is also allowed for plain <code>enum</code> in C++11. If no underlying type is specified for a scoped enumeration, the underlying type is fixed as <code>int</code>. The underlying type of a given enumeration can be found using the <code>std::underlying_type</code> template from the <code>&lt;type_traits&gt;</code> header.</li>
	
	<li>There is no implicit conversion to and from the underlying type, though such a conversion can be done explicitly with a cast.</li>
</ul>

<p>This means that they are ideal for cases where there is a limited set of values, and there are several such cases in the C++ Standard itself: <code>std::errc</code>, <code>std::pointer_safety</code>, and <code>std::launch</code> for example. The lack of implicit conversions are particularly useful here, as it means that you cannot pass raw integers such as 3 to a function expecting a scoped enumeration: you have to pass a value of the enumeration, though this is of course true for unscoped enumerations as well. The lack of implicit conversions <em>to</em> integers does mean that you can overload a function taking a numeric type without having to worry about any potential ambiguity due to numeric conversion orderings.</p>

<h2>Bitmask types</h2>

<p>Whereas the implicit conversions of plain enumerations mean that expressions such as <code>red | green</code> and <code>red &amp; green</code> are valid if <code>red</code> and <code>green</code> are enumerators, the downside is that <code>red * green </code>or <code>red / green</code> are equally valid, if nonsensical. With scoped enumerations, none of these expressions are valid unless the relevant operators are defined, which means you can explicitly define what you want to permit.</p>

<p><code>std::launch</code> is a scoped enumeration that is also a bitmask type. This means that expressions such as:</p>

<pre class="programlisting">
  std::launch::async | std::launch::deferred</pre>

<p>and </p>

<pre class="programlisting">
  std::launch::any &amp; std::launch::async</pre>

<p>are valid, but you cannot multiply or divide launch policies. The requirements on such a type are defined in section 17.5.2.1.3 [bitmask.types] of the C++ Standard, but they amount to providing definitions for the operators <code>|</code>, <code>&amp;</code>, <code>^</code>, <code>~</code>, <code>|=</code>, <code>&amp;=</code> and <code>^=</code> with the expected semantics.</p>

<p>The implementation of these operators is trivial, so it is easy to create your own bitmask types, but having to actually define the operators for each bitmask type is undesirable.</p>

<h2>Bitmask operator templates</h2>

<p>These operators can be templates, so you could define a template for each operator, e.g.</p>
<pre class="programlisting">
  template&lt;typename E&gt;
  E operator|(E lhs,E rhs){
    typedef typename
      std::underlying_type&lt;E&gt;::type underlying;
    return static_cast&lt;E&gt;(
      static_cast&lt;underlying&gt;(lhs) 
    | static_cast&lt;underlying&gt;(rhs));
  }</pre>
  
<p>Then you could write <code>mask::x | mask::y</code> for some enumeration <code>mask</code> with enumerators <code>x</code> and <code>y</code>. The downside here is that it is too greedy: every type will match this template. Not only would you would be able to write:</p>

<pre class="programlisting">
  std::errc::bad_message | std::errc::broken_pipe</pre>

<p>which is clearly nonsensical, but you would also be able to write:</p>

<pre class="programlisting">
  &quot;some string&quot; | &quot;some other string&quot;</pre>
  
<p>though this would give a compile error on the use of <code>std::underlying_type</code>, since it is only defined for enumerations. There would also be potential clashes with other overloads of <code>operator|</code>, such as the one for <code>std::launch</code>.</p>

<p>What is needed is a constrained template, so only those types which you want to support the operator will match.</p>

<h2>SFINAE to the rescue</h2>

<p>SFINAE is a term coined by David Vandevoorde and Nicolai Josuttis in their book <em>C++ Templates: The Complete Guide</em>. It stands for â€˜Substitution Failure is Not an Errorâ€™, and highlights a feature of expanding function templates during overload resolution: if substituting the template parameters into the function declaration fails to produce a valid declaration then the template is removed from the overload set without causing a compilation error.</p>

<p>This is a key feature used to constrain templates, both within the C++ Standard Library, and in many other libraries and application code. It is such a key feature that the C++ Standard Library even provides a library facility to assist with its use: <code>std::enable_if</code>.</p>

<p>We can therefore use it to constrain our template to just those scoped enumerations that we want to act as bitmasks (see Listing 1).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template&lt;typename E&gt;
struct enable_bitmask_operators{
    static constexpr bool enable=false;
};

template&lt;typename E&gt;

typename
  std::enable_if&lt;enable_bitmask_operators&lt;E&gt;
     ::enable,E&gt;::type

operator|(E lhs,E rhs){
  typedef typename std::underlying_type&lt;E&gt;
    ::type underlying;
  return static_cast&lt;E&gt;(
    static_cast&lt;underlying&gt;(lhs) 
  | static_cast&lt;underlying&gt;(rhs));
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>If <code>enable_bitmask_operators&lt;E&gt;::enable</code> is <code>false</code> (which it is unless specialized) then:</p>

<pre class="programlisting">
  std::enable_if&lt;enable_bitmask_operators&lt;E&gt;
     ::enable,E&gt;::type</pre>
	 
<p>will not exist, and so this <code>operator|</code> will be discarded without error. It will thus not compete with other overloads of <code>operator|</code>, and the compilation will fail if and only if there are no other matching overloads.</p>

<pre class="programlisting">
  std::errc::bad_message | std::errc::broken_pipe</pre>
  
<p>will thus fail to compile, whilst </p>

<pre class="programlisting">
  std::launch::async | std::launch::deferred</pre>
  
<p>will continue to work.</p>

<p>For those types that we do want to work as bitmasks, we can then just specialize <code>enable_bitmask_operators</code>:</p>

<pre class="programlisting">
    enum class my_bitmask{
        first=1,second=2,third=4
    }:
    template&lt;&gt;
    struct enable_bitmask_operators&lt;my_bitmask&gt;{
        static constexpr bool enable=true;
    };</pre>
	
<p>Now, <code>std::enable_if&lt;enable_bitmask_operators&lt;E&gt;::enable,E&gt;::type</code> will exist when <code>E</code> is <code>my_bitmask</code>, so this operator| will be considered by overload resolution, and <code>my_bitmask::first | my_bitmask::second</code> will now compile.</p>

<h2>Final code</h2>

<p>The final code is available as a header file along with a simple example demonstrating its use (see <a href="https://www.justsoftwaresolutions.co.uk/cplusplus/using-enum-classes-as-bitfields.html">https://www.justsoftwaresolutions.co.uk/cplusplus/using-enum-classes-as-bitfields.html</a>). It has been tested with g++ 4.7, 4.8 and 4.9 in C++11 mode, and with MSVC 2012 and 2013, and is released under the Boost Software License.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
