Note that there are some explanatory texts on larger screens.

plurals
  1. POPopulate An Array Using Constexpr at Compile-time
    primarykey
    data
    text
    <p>I would like to populate an array of enum using constexpr. The content of the array follows a certain pattern.</p> <p>I have an enum separating ASCII character set into four categories.</p> <pre><code>enum Type { Alphabet, Number, Symbol, Other, }; constexpr Type table[128] = /* blah blah */; </code></pre> <p>I would like to have an array of 128 <code>Type</code>. They can be in a structure. The index of the array will be corresponding to the ASCII characters and the value will be the <code>Type</code> of each character.</p> <p>So I can query this array to find out which category an ASCII character belongs to. Something like</p> <pre><code>char c = RandomFunction(); if (table[c] == Alphabet) DoSomething(); </code></pre> <p>I would like to know if this is possible without some lengthy macro hacks.</p> <p>Currently, I initialize the table by doing the following.</p> <pre><code>constexpr bool IsAlphabet (char c) { return ((c &gt;= 0x41 &amp;&amp; c &lt;= 0x5A) || (c &gt;= 0x61 &amp;&amp; c &lt;= 0x7A)); } constexpr bool IsNumber (char c) { /* blah blah */ } constexpr bool IsSymbol (char c) { /* blah blah */ } constexpr Type whichCategory (char c) { /* blah blah */ } constexpr Type table[128] = { INITIALIZE }; </code></pre> <p>where <code>INITIALIZE</code> is the entry point of some very lengthy macro hacks. Something like</p> <pre><code>#define INITIALIZE INIT(0) #define INIT(N) INIT_##N #define INIT_0 whichCategory(0), INIT_1 #define INIT_1 whichCategory(1), INIT_2 //... #define INIT_127 whichCategory(127) </code></pre> <p>I would like a way to populate this array or a structure containing the array without the need for this macro hack...</p> <p>Maybe something like</p> <pre><code>struct Table { Type _[128]; }; constexpr Table table = MagicFunction(); </code></pre> <p>So, the question is how to write this <code>MagicFunction</code>?</p> <p><strong>Note:</strong> I am aware of cctype and likes, this question is more of a <code>Is this possible?</code> rather than <code>Is this the best way to do it?</code>.</p> <p>Any help would be appreciated.</p> <p>Thanks,</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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