title: Metaprogramming C/C++ using the preprocessor
body: <p>So I have this huge tree that is basically a big switch/case with string keys and different function calls on one common object depending on the key and one piece of metadata.</p>
  
  <p>Every entry basically looks like this</p>
  
  <pre><code>} else if ( strcmp(key, "key_string") == 0) {
      ((class_name*)object)-&gt;do_something();
  } else if ( ...
  </code></pre>
  
  <p>where <code>do_something</code> can have different invocations, so I can't just use function pointers. Also, some keys require object to be cast to a subclass.</p>
  
  <p>Now, if I were to code this in a higher level language, I would use a dictionary of lambdas to simplify this.</p>
  
  <p>It occurred to me that I could use macros to simplify this to something like</p>
  
  <pre><code>case_call("key_string", class_name, do_something());
  case_call( /* ... */ )
  </code></pre>
  
  <p>where <code>case_call</code> would be a macro that would expand this code to the first code snippet.</p>
  
  <p>However, I am very much on the fence whether that would be considered good style. I mean, it would reduce typing work and improve the DRYness of the code, but then it really seems to abuse the macro system somewhat. </p>
  
  <p>Would you go down that road, or rather type out the whole thing? And what would be your reasoning for doing so?</p>
  
  <p><strong>Edit</strong></p>
  
  <p>Some clarification:</p>
  
  <p>This code is used as a glue layer between a simplified scripting API which accesses several different aspects of a C++ API as simple key-value properties. The properties are implemented in different ways in C++ though: Some have getter/setter methods, some are set in a special struct. Scripting actions reference C++ objects casted to a common base class. However, some actions are only available on certain subclasses and have to be cast down.</p>
  
  <p>Further down the road, I may change the actual C++ API, but for the moment, it has to be regarded as unchangeable. Also, this has to work on an embedded compiler, so boost or C++11 are (sadly) not available.</p>