Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing a mixin (?) to make stream i/o easier
    primarykey
    data
    text
    <p>Since many students I work with on common code have some problems comprehending proper stream operator overloading, I tried to create a helper template (don't know if this is a real mixin) to facilitate the code and insure correct operator implementation. Here it comes:</p> <pre><code>template&lt;typename T&gt; struct IoEnabled { friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, T const&amp; val) { return val.print(out); } friend std::istream&amp; operator&gt;&gt;(std::istream&amp; in, T&amp; val) { return val.scan(in); } friend QTextStream&amp; operator&lt;&lt;(QTextStream&amp; out, T const&amp; val) { return val.print(out); } friend QTextStream&amp; operator&gt;&gt;(QTextStream&amp; in, T&amp; val) { return val.scan(in); } friend QDebug operator&lt;&lt;(QDebug dbg,T const&amp; val){ std::stringstream myStream; myStream &lt;&lt; val; dbg.nospace() &lt;&lt; myStream.str().c_str(); return dbg; } }; </code></pre> <p>Inheriting class:</p> <pre><code>class Foo: private IoEnabled&lt;Foo&gt; { protected: int mData; public: template&lt;typename U&gt; U&amp; scan(U&amp; in) { in &gt;&gt; mData; return in; } template&lt;typename U&gt; U&amp; print(U&amp; out) const { out &lt;&lt; mData; return out; } } </code></pre> <p>The downsides of this implementation as far as I see them at the moment:</p> <ul> <li>Does not work for 3rd party types</li> <li>Includes inheritance and thus tight coupling with the IoClass although not every user might need Io for a certain type</li> </ul> <p>The ups:</p> <ul> <li>It works ;-)</li> <li>Similar stream classes can be added without modifying all classes and withou writing specific new code for every class</li> </ul> <p>Since I'm not very experienced in the usage of mixins and tend to violate coding guidelines once in a while, I'd like to know if this is an appropriate usage of a mixin or how one could obtain a similar effect with another more suitable technique.</p> <p>Many Thanks, Martin</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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