Per-file enabling of scope guards <p>Here's a little problem I've been thinking about for a while now that I have not found a solution for yet.</p> <p>So, to start with, I have this function guard that I use for debugging purpose:</p> <pre><code>class FuncGuard { public: FuncGuard(const TCHAR* funcsig, const TCHAR* funcname, const TCHAR* file, int line); ~FuncGuard(); // ... }; #ifdef _DEBUG #define func_guard() FuncGuard __func_guard__( TEXT(__FUNCSIG__), TEXT(__FUNCTION__), TEXT(__FILE__), __LINE__) #else #define func_guard() void(0) #endif </code></pre> <p>The guard is intended to help trace the path the code takes at runtime by printing some information to the debug console. It is intended to be used such as:</p> <pre><code>void TestGuardFuncWithCommentOne() { func_guard(); } void TestGuardFuncWithCommentTwo() { func_guard(); // ... TestGuardFuncWithCommentOne(); } </code></pre> <p>And it gives this as a result:</p> <pre> ..\tests\testDebug.cpp(121): Entering[ void __cdecl TestGuardFuncWithCommentTwo(void) ] ..\tests\testDebug.cpp(114): Entering[ void __cdecl TestGuardFuncWithCommentOne(void) ] Leaving[ TestGuardFuncWithCommentOne ] Leaving[ TestGuardFuncWithCommentTwo ] </pre> <p>Now, one thing that I quickly realized is that it's a pain to add and remove the guards from the function calls. It's also unthinkable to leave them there permanently as they are because it drains CPU cycles for no good reasons and it can quickly bring the app to a crawl. Also, even if there were no impacts on the performances of the app in debug, there would soon be a flood of information in the debug console that would render the use of this debug tool useless.</p> <p>So, I thought it could be a good idea to enable and disable them on a per-file basis.</p> <p>The idea would be to have all the function guards disabled by default, but they could be enabled automagically in a whole file simply by adding a line such as</p> <pre><code>EnableFuncGuards(); </code></pre> <p>at the top of the file.</p> <p>I've thought about many a solutions for this. I won't go into details here since my question is already long enough, but let just say that I've tried more than a few trick involving macros that all failed, and one involving explicit implementation of templates but so far, none of them can get me the actual result I'm looking for.</p> <p>Another restricting factor to note: The header in which the function guard mechanism is currently implemented is included through a precompiled header. I know it complicates things, but if someone could come up with a solution that could work in this situation, that would be awesome. If not, well, I certainly can extract that header fro the precompiled header.</p> <p>Thanks a bunch in advance!</p>