title: C++ template static integer constants: out of class definition
body: <p>This question is about the relationship between templates and static integral constants in Visual Studio C++ 2013 with flag /Za. It has implications for the boost library.</p>
  
  <hr>
  
  <p>First, let us check the code without templates:</p>
  
  <pre><code>struct easy
  {
      static const int a = 5;
      const int b;
  
      easy( int b_ ) : b( std::max( b_, a ) )
      {}
  };
  
  const int easy::a;
  
  int main()
  {
      easy d_Easy( 0 );
      return 0;
  }
  </code></pre>
  
  <p>According to the manual page for <a href="http://msdn.microsoft.com/en-us/library/34h23df8.aspx" rel="nofollow noreferrer">compiler option /Za</a>: "Under the standard (/Za), you must make an out-of-class definition for data members". The example in that page and the code above declares the static constant within the class and specifies its value there. The need for the out of class definition is explained in <a href="https://stackoverflow.com/questions/3025997/c-defining-static-const-integer-members-in-class-definition">this link</a>.</p>
  
  <hr>
  
  <p>Now, let us see the problem with templates.</p>
  
  <pre><code>template&lt; class T &gt;
  struct problem
  {
      static const int a = 5;
      const int b;
  
      problem( int b_ ) : b( std::max( b_, a ) )
      {}
  };
  
  template&lt; class T &gt;
  const int problem&lt; T &gt;::a;
  
  int main()
  {
      problem&lt; char &gt; d_Bad( 666 );
      return 0;
  }
  </code></pre>
  
  <p>When compiling with /Za, the linker throws an error "LNK2019: unresolved external symbol". That error does not appear with option /Ze.The major problem is that some boost libraries use BOOST_STATIC_CONSTANT and BOOST_NO_INCLASS_MEMBER_INITIALIZATION in code similar to the above snipet.</p>
  
  <hr>
  
  <p>Hacking some:</p>
  
  <pre><code>template&lt; class T &gt;
  struct fixed
  {
      static const int a;
      const int b;
  
      fixed( int b_ ) : b( std::max( b_, a ) )
      {}
  };
  
  template&lt; class T &gt;
  const int fixed&lt; T &gt;::a = 5;
  
  int main()
  {
      fixed&lt; char &gt; d_Good( 777 );
      return 0;
  }
  </code></pre>
  
  <p>This code now compiles with /Za.</p>
  
  <p><strong>Questions:</strong></p>
  
  <p>1) What does the C++11 standard say about templates and static integral constants? Can/must they have an out of class definition but their value be provided in the class definition?</p>
  
  <p>2) Does boost have some workarounds?</p>
  
  <hr>
  
  <p><strong>UPDATE</strong></p>
  
  <p>It is important to keep the <code>std::max</code> in the code because (I think) it tries to get the reference to its parameters. If one uses <code>b_&lt;a</code> then the compiler simply optimizes those constants away.</p>