Note that there are some explanatory texts on larger screens.

plurals
  1. POFunctional-Programming Style in C++ Macros: Is this documented anywhere?
    text
    copied!<p>Reading some C++ code I came across what I'll call a "functional" use of function Macros roughly as follows (this is a totally stylized example to make the point):</p> <pre><code>#define TOP_LEVEL(ARG1) \ ARG1("foo1","bar1") \ ARG1("foo2","bar2") #define NEXT_LEVEL(ARG2A, ARG2B) \ cout &lt;&lt; ARG2A &lt;&lt; " and " &lt;&lt; ARG2B; TOP_LEVEL(NEXT_LEVEL) </code></pre> <p>I'm relatively new to the language and at first I couldn't figure this out, but then I ran it through just the preprocessor (<code>g++ -E</code>) and lo and behold it resolves to:</p> <pre><code>cout &lt;&lt; "foo1" &lt;&lt; " and " &lt;&lt; "bar1"; cout &lt;&lt; "foo2" &lt;&lt; " and " &lt;&lt; "bar2"; </code></pre> <p>Do you see what it did there? It passed the Macro NEXT_LEVEL <strong>like a function pointer</strong> to the Macro TOP_LEVEL. Seeing how useful this could potentially be, I wanted to learn more about it: passing around functions to other functions is <a href="http://en.wikipedia.org/wiki/First-class_function" rel="nofollow">pretty sophisticated stuff</a> and there must be at least something more to say about the technique. </p> <p>Yet despite a ton of Googling I can't find evidence that this feature of the preprocessor even exists, let alone anything approaching documentation: <a href="http://www.cplusplus.com/doc/tutorial/preprocessor/" rel="nofollow">here</a>, <a href="http://gcc.gnu.org/onlinedocs/cpp/Macros.html" rel="nofollow">here</a>, <a href="http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=%2Fcom.ibm.vacpp6m.doc%2Flanguage%2Fref%2Fclrc09cpxmac.htm" rel="nofollow">here</a> and <a href="http://www.cprogramming.com/tutorial/cpreprocessor.html" rel="nofollow">here</a> are just four examples of Macro tutorials that skip right past this; the last even has a section called "Advanced Macro tricks" - surely this qualifies!?</p> <p>(Please note this is totally different than simply calling a function macro with another <strong>evaluated</strong> function macro as an argument- FOO(BAR(2)) is much more straightforward.) </p> <p>My questions are:</p> <ul> <li>Is there an actual name for this behavior?</li> <li>Is it documented anywhere?</li> <li>It is commonly used, or are there well known pitfalls, etc.?</li> </ul>
 

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