Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For some reason I found the problem description easy to misunderstand, but the linked code makes it clear. In C++11 it's easy:</p> <pre><code>#define SETUP_ENUM_LENGTH(enum_type, length) \ static constexpr int enum_length(enum_type*) { return length; } </code></pre> <p>and a </p> <pre><code> for (int i = 0; i &lt; enum_length((Enum*)0); ++i) { </code></pre> <p>in the right place. Here's a sample:</p> <pre><code>#include &lt;iostream&gt; #include &lt;functional&gt; #include &lt;boost/preprocessor/variadic/size.hpp&gt; /** * Macro to setup an enum completely. * First parameter is the name, following are the states as plain text. */ #define DEF_ENUM(name, ...) \ enum class name : uint8_t { __VA_ARGS__ }; \ SETUP_ENUM_LENGTH(name, BOOST_PP_VARIADIC_SIZE(__VA_ARGS__)) /** * Once an enum class is defined, this macro makes the size publicly available. * Needed by enum_array. Already included in DEF_ENUM. */ #define SETUP_ENUM_LENGTH(enum_type, length) \ static constexpr int enum_length(enum_type*) { return length; } /** * Function to iterate over all elements of an enum. */ template&lt;typename Enum&gt; void enum_for_each(const std::function&lt;void(Enum e)&gt; &amp;fct) { for (int i = 0; i &lt; enum_length((Enum*)0); ++i) { fct(static_cast&lt;Enum&gt;(i)); } } namespace n { DEF_ENUM(demo,u,v,w,x,y,z,a,b,c); } namespace m { DEF_ENUM(demo,a=3,b=1,c=4,d=1,e=5); } using std::cout; int main() { enum_for_each&lt;n::demo&gt;([](n::demo e) { cout&lt;&lt;int(e); }); cout&lt;&lt;'\n'; enum_for_each&lt;m::demo&gt;([](m::demo e) { cout&lt;&lt;int(e); }); cout&lt;&lt;'\n'; int ndemo[enum_length((n::demo*)0)]; int mdemo[enum_length((m::demo*)0)]; cout &lt;&lt; sizeof ndemo &lt;&lt; ' ' &lt;&lt; sizeof mdemo &lt;&lt; '\n'; } </code></pre> <p>As a side note, that <code>static_cast&lt;Enum&gt;(i)</code> looks troublesome, does it really do the right thing with the <code>m::demo</code> enum?</p> <p>To preserve the original templated-<code>enum_length</code> usage and so make the array-allocation usage a bit prettier is easy from here, rename the function <code>enum_length_helper</code> and then</p> <pre><code>template&lt;typename Enum&gt; struct enum_length { enum result=enum_length_helper((Enum*)0); }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload