title: Schwarz Counter and variadic template
body: <p>For people who never heard of "Schwarz Counter", please refer to <a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter" rel="nofollow">this</a> wikibook page.</p>
  
  <p>I'm trying to implement this idiom with C++11 template, everything works fine except when the template argument ISN'T default constructible. Here is my implementation: (See the code comments for the question)</p>
  
  <pre><code>#include &lt;type_traits&gt;
  
  template&lt;typename T&gt;
  class Single {
  public:
      static T&amp; get() {
          return reinterpret_cast&lt;T&amp;&gt;(instance.storage);
      }
  
  private:
      struct Instance {
          enum { kSize = sizeof(T), kAlign = std::alignment_of&lt;T&gt;::value };
  
          int counter;
          typename std::aligned_storage&lt;kSize, kAlign&gt;::type storage;
  
          template&lt;typename... Arg&gt;
          Instance(Arg&amp;&amp;... param) {
              if (counter++ == 0) {
                  new (&amp;storage) T(param...);
              }
          }
  
          ~Instance() {
              if (--counter == 0) {
                  reinterpret_cast&lt;T&amp;&gt;(storage).~T();
              }
          }
      };
  
      static Instance instance;
  };
  
  // The following won't compile if T isn't default constructible.
  // I want to get rid of the definition in this case, and let the
  // users of this template to provide their own definitions.
  // I'd like to keep the it when T is default constructible, because
  // most of the time T is (according to my experience, most global 
  // objects are constructed without arguments, singletons are
  // essentially global objects).
  //
  // So, basically I want something like this:
  // #if std::is_default_constructible&lt;T&gt;::value
  //     template&lt;typename T&gt;
  //     ...;
  // #endif
  // Could this be done in C++11 ? If not, how about C++14 ?
  template&lt;typename T&gt;
  typename Single&lt;T&gt;::Instance Single&lt;T&gt;::instance;
  </code></pre>
  
  
  
  <p>BTW, define a singleton with this template is very simple if the class is default constructible, for example:</p>
  
  
  
  <pre class="lang-js prettyprint-override"><code>class Y {
      friend class Single&lt;Y&gt;;
      Y(int, int) { std::cout &lt;&lt; "Y()\n"; }
      ~Y() { std::cout &lt;&lt; "~Y()\n"; }
  };
  
  class X {
      friend class Single&lt;X&gt;;
      X() { std::cout &lt;&lt; "X()\n"; }
      ~X() { std::cout &lt;&lt; "~X()\n"; }
  };
  
  int main() {
      auto&amp; x = Single&lt;X&gt;::get();
      // auto&amp; g = Single&lt;Y&gt;::get(); // oops
      return 0;
  }
  </code></pre>