Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ Constant preprocessor macros and templates
    text
    copied!<p>So say I have the following very simple macro, along with a bit of code to output it:</p> <pre><code>#define SIMPLEHASH(STRING) STRING[1] + STRING[2] + STRING[3] std::cout &lt;&lt; SIMPLEHASH("Blah"); </code></pre> <p>This outputs 309, and if you view the assembly you can see:</p> <pre><code>00131094 mov ecx,dword ptr [__imp_std::cout (132050h)] 0013109A push 135h 0013109F call dword ptr [__imp_std::basic_ostream&lt;char,std::char_traits&lt;char&gt; &gt;::operator&lt;&lt; (13203Ch)] </code></pre> <p>Where <code>135h</code> translates nicely into 309 decimal. Everything was compiled away to a constant.</p> <hr> <p>Now, say you have a template class as such:</p> <pre><code>template&lt;int X&gt; class Printer{ public: void Print(){ std::cout &lt;&lt; X; } }; </code></pre> <p>Then the following will nicely print the number 32:</p> <pre><code>Printer&lt;32&gt; p; p.Print(); </code></pre> <hr> <p>Both these things work individually, the problem comes when you try to combine them:</p> <pre><code>#define SIMPLEHASH(STRING) STRING[1] + STRING[2] + STRING[3] Printer&lt;SIMPLEHASH("Blah")&gt; p; p.Print(); </code></pre> <p>In visual studio this gives:</p> <blockquote> <p>1>.\ShiftCompare.cpp(187) : error C2975: 'X' : invalid template argument for 'Printer', expected compile-time constant expression<br> 1> .\ShiftCompare.cpp(127) : see declaration of 'X'</p> </blockquote> <p>Despite the fact that <code>SIMPLEHASH("Blah")</code> can be reduced to a constant at compile time, as seen in the first example.</p> <p>So, what gives, is there a way to tell the compiler "evaluate this first"? are templates naturally "before" macros in preprocessor evaluation?</p> <p>Does anyone see any way I can get these two to work together?</p>
 

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