Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Below is some code that I recall seeing a while ago in a compiler construction class. I thought it was particularly clever (if not 'clean') so I held on to it. </p> <p>From <a href="http://www.cs.colorado.edu/~main/a++/tree.h" rel="nofollow noreferrer">http://www.cs.colorado.edu/~main/a++/tree.h</a></p> <pre><code> // If data of type T can be printed with the usual &lt;&lt; operator, then // print&lt;T&gt;(out, p) will interpret *p as a T object and print its // value to out. Otherwise, a message is printed to out, indicating // that objects of type T are not printable. template&lt;typename T&gt; void print(std::ostream&amp; out, const void* p) { // The first part of this code sets an enum value, is_printable, to // be 1 if the data type T can be printed with the usual &lt;&lt; // operator. Otherwise, is_printable is set to zero. The programming // technique is based on a note from Herb Sutter at // http://www.gotw.ca/gotw/071.htm class object { public: object(T convert) { }; }; char operator &lt;&lt; (std::ostream&amp;, const object&amp;); enum { is_printable = sizeof(std::cout &lt;&lt; (*static_cast&lt;T*&gt;(0))) == sizeof(char) ? 0 : 1 }; // Notice that the boolean expression in the if-statement is known at // compile time, so that only one of the two output statements will be // compiled into object code. if (is_printable) out &lt;&lt; *static_cast&lt;const T*&gt;(p); else out &lt;&lt; "(value of type " &lt;&lt; typeid(T).name() &lt;&lt; " cannot be printed)"; } </code></pre> <p>When you construct your container object, hold a pointer to the print function for the variable:</p> <pre><code>void (*printer)(std::ostream&amp;, const void*); printer = print&lt;T&gt;; </code></pre> <p>Then later use the printer() function to display the contained value if possible.</p> <p>Hope this helps.</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