title: Disabling some code completely in standard c++?
body: <p>Trying to understand what the best way to disable code parts currently is with all the fancy features we have in C++ nowadays.</p>
  
  <p>My test implementations are as follows.</p>
  
  <p>1) Using <code>static if</code> (c++17 and newer):</p>
  
  <pre><code>inline constexpr bool LogEnabled = false; // this would come from, say, Makefile
  
  struct logger
  {
      static logger &amp;instance()
      {
          static logger lg;
          return lg;
      }
  
      inline void log(std::string_view msg)
      {
          if constexpr (LogEnabled)
          {
              cout &lt;&lt; msg &lt;&lt; endl;
          }
      }
  };
  </code></pre>
  
  <p>2) Using <code>template specialization</code> (fine for c++98 i believe):</p>
  
  <pre><code>inline constexpr bool LogEnabled = false; 
  
  struct logger
  {
      static logger &amp;instance()
      {
          static logger lg;
          return lg;
      }
  
      template &lt;bool Enable = LogEnabled&gt;
      inline void log(std::string_view msg)
      {
          // nop version
      }
  
      template &lt;&gt;
      inline void log&lt;true&gt;(std::string_view msg)
      {
          cout &lt;&lt; msg &lt;&lt; endl;
      }
  };
  </code></pre>
  
  <p>3) I had an idea to use <code>SFINAE</code> with <code>std::enable_if</code> but could not quite get it to work.</p>
  
  <p>Here is the call site requirement:</p>
  
  <pre><code>int main()
  {
      logger::instance().log("bruh");
      return 0;
  }
  </code></pre>
  
  <p>So what happens if you compile both versions with <code>-O3 -std=c++17</code> is that the optimizer completely removes generated code for the whole log line in main leaving main look like this:</p>
  
  <pre><code>main:                                   # @main
      xor     eax, eax
      ret
  </code></pre>
  
  <p>This is great. Both versions do exactly what we want and completely remove the code. But this only happens if the optimization flag is used. If we have <code>-O0</code> then the call to logger remains even tho it's a <code>nop</code> in both cases. </p>
  
  <p>Is there a better way to do this in clean C++ (please no preprocessor from all the way back to the 90s). Something that would not need the optimizer to do work. Maybe SFINAE could do that better? Can anyone please show an example of a SFINAE version of this?</p>
  
  <p>Thank you!</p>