title: Cleanest way for conditional code instantiation in C++ template
body: <p>I'm trying to get the following C++ code running:</p>
  
  <pre><code>#include &lt;cmath&gt;
  
  template&lt;typename T, bool&gt; class ConditionalData {
  };
  
  template &lt;typename T&gt; class ConditionalData&lt;T, false&gt; {
  };
  
  template &lt;typename T&gt; class ConditionalData&lt;T, true&gt; {
  private:
      T data;
  public:
      void setData(T _data) { data = _data; }
  };
  
  
  template&lt;bool hasdata&gt; class A {
  public:
      A() {
          ConditionalData&lt;double,hasdata&gt; data;
          if (hasdata) {
              data.setData(sin(cos(123.4)));
          }
      }
  };
  
  
  int main(int argNum, const char**argData) {
      A&lt;false&gt; test1;
      A&lt;true&gt; test2;
      return 0;
  }
  </code></pre>
  
  <p>Essentially, I want to implement a templated class A in which certain operations are executed depending on the template parameter. These operations need local variables, which I only want to be allocated if needed. The problem that I'm having here is that the body of the </p>
  
  <pre><code>if (hasdata) {
      data.setData(3);
  }
  </code></pre>
  
  <p>condition is also instantiated for hasdata=false, which does not compile (using g++ 5.2). Any ideas how to get this done in the cleanest way without splitting the body of A::A() into pieces? </p>
  
  <p>The source code above is a minimal non-working example. The real implementation for A::A() is relatively long, with the parts dependent on "hasdata" being distributed evenly over the code. Also, the "typename T" for which the class A will be used is a relatively complex class with heavy-weight constructors/destructors, so I want the instances of T to only be allocated when hasdata=true. Finally, in the data.setData(...) calls, there can be complex computations in the "...", which should only be performed if needed.</p>