title: template friend function in another namespace and CRTP
body: <p>This has been driving me crazy for the past couple hours, and I cannot seem to get around this problem. I have distilled the problem down to these 60 lines of code (including a main function).</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  namespace n1 {
  
  // the general definition
  template &lt;class X, class Y&gt; void f(X&amp;, const Y&amp;)
  {
      std::cout &lt;&lt; "general template definition.\n";
  }
  
  } // namespace n1
  namespace n2 {
  
  // CRTP
  template &lt;class Derived&gt; class A 
  {
      int data;
  
      // partial function template specialization for n1::f, and declare
      // it a friend too, so that it may access the data attribute of A
      template &lt;class Y&gt; friend void n1::f(A&lt;Derived&gt;&amp; a, const Y&amp; y);
  
  }; // class A
  
  } // namespace n2
  namespace n1 {
  
  // implementation for this particular function template specialization
  template &lt;class Derived, class Y&gt; void f(n2::A&lt;Derived&gt;&amp; a, const Y&amp; y)
  {
      std::cout &lt;&lt; "partial template specialization: " &lt;&lt; a.data &lt;&lt; "\n";
  }
  
  } // namespace n1
  namespace n2 {
  
  // Another class!
  class B : public A&lt;B&gt; 
  {
  
  }; // class B    
  } // namespace n2
  namespace n1 {
  
  // --------------------
  // tricky part is here!
  // --------------------
  template &lt;class Y&gt; void f(n2::B&amp; b, const Y&amp; y)
  {
      // FAIL! not a friend! How?
      f(static_cast&lt;n2::A&lt;n2::B&gt;&amp;&gt;(b), y);
  }
  
  } // namespace n1
  
  int main()
  {
      n2::B b;
      int x;
      n1::f(b, x); // should print "partial template specialization"
      return 0;
  }
  </code></pre>
  
  <p>So, what I "want" is to have the compiler select my function template specialization of <code>n1::f</code> whenever it is invoked with a concrete subclass of <code>A&lt;Derived&gt;</code>. In order to make sure that the compiler favors my specialization, I need to supply, for every subclass (<code>B</code> in this case), also a template specialization for <code>n1::f</code> that simply delegates the call. When that happens, I expect the <code>data</code> member variable of <code>A&lt;Derived&gt;</code> to be accessible to <code>n1::f</code>, because I declare <code>n1::f</code> to be a friend of <code>A&lt;Derived&gt;</code>. However, GCC complains that <code>A&lt;Derived&gt;::data</code> is private and inaccessible, <a href="http://coliru.stacked-crooked.com/a/2f36f9bdf9edc7f9" rel="nofollow noreferrer">see this snippet on Coliru</a>.</p>
  
  <p>Is this construction possible? If so, how can I get around the compiler complaining that <code>A&lt;Derived&gt;::data</code> is not accessible? (Making it public is not an option).</p>