Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use friend definition, which will define the operator in the surrounding namespace of the class, and make it only visible to operator overloading resolution (not callable manually using the ::operator&lt;&lt;... syntax):</p> <pre><code>class Logger { public: Logger(); ~Logger(); std::ostream* out_stream; template &lt;typename T&gt; friend Logger&amp; operator&lt;&lt; (Logger&amp; logger, T thing) { *logger.out_stream &lt;&lt; thing; return logger; } /* special treatment for std::wstring. just overload the operator! No need * to specialize it. */ friend Logger&amp; operator&lt;&lt; (Logger&amp; logger, const std::wstring &amp; wstr) { /* do something here */ } }; </code></pre> <p>The alternative, to keep your code as it is and just make the operator&lt;&lt; template a friend, you add this line into your class definition:</p> <pre><code>template &lt;typename T&gt; friend Logger&amp; operator&lt;&lt; (Logger&amp; logger, T thing); </code></pre> <p>For the manipulator problem, i will just give you my code i write some time ago:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; template&lt;typename Char, typename Traits = char_traits&lt;Char&gt; &gt; struct logger{ typedef std::basic_ostream&lt;Char, Traits&gt; ostream_type; typedef ostream_type&amp; (*manip_type)(ostream_type&amp;); logger(ostream_type&amp; os):os(os){} logger &amp;operator&lt;&lt;(manip_type pfn) { if(pfn == static_cast&lt;manip_type&gt;(std::endl)) { time_t t = time(0); os &lt;&lt; " --- " &lt;&lt; ctime(&amp;t) &lt;&lt; pfn; } else os &lt;&lt; pfn; return *this; } template&lt;typename T&gt; logger &amp;operator&lt;&lt;(T const&amp; t) { os &lt;&lt; t; return *this; } private: ostream_type &amp; os; }; namespace { logger&lt;char&gt; clogged(cout); } int main() { clogged &lt;&lt; "something with log functionality" &lt;&lt; std::endl; } </code></pre> <p>};</p> <p><b>Note that it is std::hex , but not std::ios::hex</b>. The latter is used as a manipulator flag for the <code>setf</code> function of streams. Note that for your example, tho, no special treatment of manipulators is required. The above special treatment of std::endl is only needed because i do stream the time in addition when std::endl is used.</p>
 

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