Note that there are some explanatory texts on larger screens.

plurals
  1. POfriend of specialized template class (C++)
    text
    copied!<pre><code>#include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; class test { T y; public: test(T k) : y(k) {} friend int a(T&amp; x); }; template &lt;typename T&gt; int a(T&amp; x) { cout &lt;&lt; x.y; return 9; } template &lt;&gt; class test&lt;int&gt; { int y; public: test(int k) : y(k) {} friend int a(int&amp; x); }; template &lt;&gt; int a&lt;int&gt;(int&amp; x) { cout &lt;&lt; "4"; return 0; } int main(int argc, char* argv[]) { test&lt;int&gt; z(3); a(z); return 0; } </code></pre> <p>I want to make a friend class of test class (in a real case, it was a operator&lt;&lt; of ofstream). But I have no idea how to define template friend function of specialized class.</p> <p>Besides, the code above shows this compile error message;</p> <blockquote> <p>error C2248: 'test::y' : cannot access private member declared in class 'test'</p> </blockquote> <p><strong>Question added;</strong></p> <p>Aaron McDaid works fine for me, but I was trying to overload operator&lt;&lt; of ofstream class. </p> <pre><code>friend ofstream&amp; operator&lt;&lt; &lt;test&lt;int&gt;&gt; (ofstream&amp; os, const test&lt;int&gt;&amp; t); </code></pre> <p>I added code above to test class and</p> <pre><code>template&lt;&gt; ofstream&amp; operator&lt;&lt; &lt;test&lt;int&gt; &gt; (ofstream&amp; os, const test&lt;int&gt;&amp; t) { os &lt;&lt; t.y; return os; } </code></pre> <p>used code above. But it looks like I cannot use os &lt;&lt; t.y (which is <em>int</em>) I don't understand why this happens. The error message is</p> <blockquote> <p>error C2027: use of undefined type 'std::basic_ofstream&lt;_Elem,_Traits>'</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload