Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to overload operator<< that doesn't take or return ostream
    text
    copied!<p><strong>Original Question</strong></p> <p>I am writting a logging class where the goal is to be able to do this:</p> <pre><code>// thread one Logger() &lt;&lt; "Some string" &lt;&lt; std::ios::hex &lt;&lt; 45; // thread two Logger() &lt;&lt; L"Some wide string" &lt;&lt; std::endl; </code></pre> <p>Currently my Logger header looks something like this:</p> <pre><code>#pragma once; #include &lt;ostream&gt; class Logger { public: Logger(); ~Logger(); std::ostream* out_stream; }; template &lt;typename T&gt; Logger&amp; operator&lt;&lt; (Logger&amp; logger, T thing) { *logger.out_stream &lt;&lt; thing; return logger; } </code></pre> <p>Some notes about this class:</p> <ol> <li>Cross platform compatibility is not an issue.</li> <li>Inside of Logger.cpp there is a singleton class that takes care of creating the "real" ostream.</li> <li>The Logger constructor and deconstructor perform the necessary locking of the singleton.</li> </ol> <p>I have three problems:</p> <ul> <li>How do I make the operator&lt;&lt; function a friend or member so I can set out_stream as private? </li> <li>How do I make the operator&lt;&lt; function work for manipulators?</li> <li>How can I add a specialization so that if T is a WCHAR* or std::wstring that it will convert it to char* or std::string before passing it to out_stream? (I can do the conversion. Losing high unicode characters isn't a problem in my case.)</li> </ul> <p><strong>Summary of things learned in answers:</strong></p> <ul> <li>Put template BEFORE friend instead of after.</li> <li>std::ios::hex is not a manipulator. std::hex is a manipulator.</li> </ul> <p><strong>End Result</strong></p> <pre><code>#pragma once #include &lt;ostream&gt; #include &lt;string&gt; std::string ConvertWstringToString(std::wstring wstr); class Logger { public: Logger(); ~Logger(); template &lt;typename T&gt; Logger&amp; operator&lt;&lt; (T data) { *out &lt;&lt; data; return *this; } Logger&amp; operator&lt;&lt; (std::wstring data) { return *this &lt;&lt; ConvertWstringToString(data); } Logger&amp; operator&lt;&lt; (const wchar_t* data) { std::wstring str(data); return *this &lt;&lt; str; } private: std::ostream* out; }; </code></pre>
 

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