title: template friend functions of template class
body: <p>I have the following template class and template function which intends to access the class' private data member:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  template&lt;class T&gt;
  class MyVar
  {
      int x;
  };
  
  template&lt;class T&gt;
  void printVar(const MyVar&lt;T&gt;&amp; var)
  {
      std::cout &lt;&lt; var.x &lt;&lt; std::endl;
  }
  
  template&lt;class T&gt;
  void scanVar(MyVar&lt;T&gt;&amp; var)
  {
      std::cin &gt;&gt; var.x;
  }
  
  struct Foo {};
  
  int main(void)
  {
      MyVar&lt;Foo&gt; a;
      scanVar(a);
      printVar(a);
      return 0;
  }
  </code></pre>
  
  <p>To declare the two functions as <code>MyVar&lt;T&gt;</code>'s friend functions, I've tried the following ways inside the declaration of <code>template&lt;class T&gt; class MyVar</code> to declare friendship. None of them works. How should I do?</p>
  
  <pre><code>template&lt;class T&gt; friend void printVar(const MyVar&amp;);
  template&lt;class T&gt; friend void scanVar(MyVar&amp;);
  // compilation error
  
  template&lt;class T&gt; friend void printVar(const MyVar&lt;T&gt;&amp;);
  template&lt;class T&gt; friend void scanVar(MyVar&lt;T&gt;&amp;);
  // compilation error
  
  friend void printVar(const MyVar&lt;T&gt;&amp;);
  friend void scanVar(MyVar&lt;T&gt;&amp;);
  // link error
  
  friend void printVar(const MyVar&amp;);
  friend void scanVar(MyVar&amp;);
  // link error too
  </code></pre>