title: C++ Templates: Partial Template Specifications and Friend Classes
body: <p>is it possible to somehow make a partial template specification a friend class? I.e. consider you have the following template class</p>
  
  <pre><code>template &lt;class T&gt; class X{
      T t;
  };
  </code></pre>
  
  <p>Now you have partial specializations, for example, for pointers</p>
  
  <pre><code>template &lt;class T&gt; class X&lt;T*&gt;{
      T* t;
  };
  </code></pre>
  
  <p>What I want to accomplish is that every possible <code>X&lt;T*&gt;</code> is a friend class of <code>X&lt;S&gt;</code> for ANY <code>S</code>. I.e. <code>X&lt;A*&gt;</code> should be a friend of <code>X&lt;B&gt;</code>.</p>
  
  <p>Of course, I thought about a usual template friend declaration in X:</p>
  
  <pre><code>template &lt;class T&gt; class X{
      template &lt;class S&gt; friend class X&lt;S*&gt;;
  }
  </code></pre>
  
  <p>However, this does not compile, g++ tells me this:</p>
  
  <p>test4.cpp:34:15: error: specialization of '<code>template&lt;class T&gt; class X</code>' must appear at namespace scope</p>
  
  <p>test4.cpp:34:21: error: partial specialization '<code>X&lt;S*&gt;</code>' declared 'friend'</p>
  
  <p>Is this not possible at all or is there some workaround?</p>
  
  <p>The reason why I am asking is that I need a constructor in <code>X&lt;T*&gt;</code> that creates this class from an arbitrary <code>X&lt;S&gt;</code> (<code>S</code> must be a subtype of <code>T</code>).</p>
  
  <p>The code looks like this:</p>
  
  <pre><code>template &lt;class T&gt; class X&lt;T*&gt;{
      T* t;
  
      template&lt;class S&gt;
      X(X&lt;S&gt; x) : t(&amp;(x.t))  {} //Error, x.t is private
  }
  </code></pre>
  
  <p>Now, the compiler complains, of course, that <code>x.t</code> is not visibile in the constructor since it is private. This is why I need a partial specialization friend class.</p>