Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing C++ templates or macros for compile time function generation
    text
    copied!<p>I have a code that runs on an embedded system and it has to run really fast. I know C and macros, and this particular project is coded mostly in C but it also uses C++ templates [increasingly more]. There is an inline function:</p> <pre><code>inline my_t read_memory(uint32 addr) { #if (CURRENT_STATE &amp; OPTIMIZE_BITMAP) return readOptimized(addr); #else return MEMORY[addr]; #endif } </code></pre> <p>This function reads from memory in an optimized fashion or conventional fashion based on the current state and a bitmap that tells whether to use optimization in a specific state or not.</p> <pre><code>#define STATE_A 0x0001 #define STATE_B 0x0010 #define STATE_C 0x0100 #define STATE_D 0x1000 #define OPTIMIZE_BITMAP 0x1010 // optimize states d and b </code></pre> <p>and during the course of execution (ok, compilation), I tried to redefine CURRENT_STATE like so:</p> <pre><code>int main(){ #define CURRENT_STATE STATE_A do_a(); #undef CURRENT_STATE #define CURRENT_STATE STATE_B do_b(); .... } </code></pre> <p>All do_X() functions make read_memory() calls. I could not make this approach work. The value of current state is always STATE_A as I can see when I use #warning statements. This is not my question, although if you can help me with this I'll be double happy. So, my question is, is there a way to do this kind of thing using templates instead of macros?</p> <p>Some more info: I have to use an inline function because I cannot export MEMORY[] and this is a library function. I really prefer not to modify the function prototype (like read_memory()...) but it will do. Also, pardon my obscurity.</p> <p>many thanks,</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