<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>0x &#187; C++</title>
	<atom:link href="http://efesx.com/category/cpp/feed/" rel="self" type="application/rss+xml" />
	<link>http://efesx.com</link>
	<description>Technical &#38; low level</description>
	<lastBuildDate>Mon, 30 Apr 2012 17:39:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Bounded size priority queue</title>
		<link>http://efesx.com/2012/04/30/bounded-size-priority-queue/</link>
		<comments>http://efesx.com/2012/04/30/bounded-size-priority-queue/#comments</comments>
		<pubDate>Sun, 29 Apr 2012 21:59:02 +0000</pubDate>
		<dc:creator>rmn</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Exceptions]]></category>
		<category><![CDATA[STL]]></category>

		<guid isPermaLink="false">http://efesx.com/?p=1333</guid>
		<description><![CDATA[A priority queue in the STL is nothing more than a regular (maximum-) heap. It is essentially an adapter built on top of another container, usually a vector. Therefore, the offered priority queue can easily contain an arbitrary number of elements (so long as memory permits). But what if we wanted to keep only the [...]]]></description>
			<content:encoded><![CDATA[<p>A <a href="http://www.sgi.com/tech/stl/priority_queue.html">priority queue</a> in the STL is nothing more than a regular (maximum-) <a href="http://en.wikipedia.org/wiki/Heap_%28data_structure%29">heap</a>. It is essentially an adapter built on top of another container, usually a <a href="http://www.sgi.com/tech/stl/Vector.html">vector</a>. Therefore, the offered priority queue can easily contain an arbitrary number of elements (so long as memory permits).</p>
<p>But what if we wanted to keep only the biggest N elements, and just have the queue dynamically throw away all other elements? I am sure you can imagine why such a behavior would be much desired: for instance, keeping the best N suggestions for a specific search term springs to mind. Unfortunately, the STL does not support such an adapter.</p>
<p><span id="more-1333"></span>I believe the following assignment is a nice introductory interview question. Something to break the ice with, if you will:<br />
Naturally, we&#8217;d want any solution to rely as heavily as possible on previously available code; How would you implement a bounded_priority_queue using only the given priority_queue from the STL?</p>
<p>At this point I would like to invite you, the readers, to take a moment and think of a solution for the provided specification. Keep in mind that the priority queue offered by the STL requires a Compare binary-function object (such as <a href="http://www.sgi.com/tech/stl/less.html">less</a>) to be used for comparing the elements held within, and only supports a few relevant operations: push, pop and size.</p>
<p>The suggested solution is as follows:<br />
Keeping a maximum heap of N elements, is exactly the same as holding a minimum heap and popping the minimal elements when the size is about to reach the limit (N) &#8212; asking for the maximal N elements is exactly the same as dropping the minimal elements until there are N elements left. We are able to convert a maximum heap to a minimum heap by altering the Compare function object mentioned above. More specifically, all we have to do is swap its two arguments.</p>
<p>I actually bumped into a need for such an implementation in my normal course of work. As Googling for an answer did not provide a solution, I thought posting one could be beneficial to others. Therefore, a nearly complete C++ solution is hereby provided:</p>
<pre class="brush: cpp; title: ; notranslate">
#include &lt;queue&gt;
#include &lt;stdexcept&gt;
#include &lt;algorithm&gt;

template &lt;class T,
          class Container = std::vector&lt;T&gt;,
          class Compare = std::less&lt;typename Container::value_type&gt;
         &gt; class bounded_priority_queue {
    public:
        typedef T value_type;
        typedef std::size_t size_type;

        explicit bounded_priority_queue (const size_type&amp; maxsize)
         : maxsize_(maxsize)
        {
            if (maxsize_ &lt; 1)
                throw std::runtime_error(&quot;bpqueue maxsize&lt;1&quot;);
        }

        void push (const value_type&amp; val) {
            if (queue_.size() &gt;= maxsize_)
                queue_.pop();
            queue_.push(val);
        }

        std::priority_queue&lt;T, Compare, Container&gt; pop_all () {
            std::priority_queue&lt;T, Compare, Container&gt; result;

            bounded_priority_queue tmp(*this);
            while (!tmp.queue_.empty()) {
                result.push(tmp.queue_.top());
                tmp.queue_.pop();
            }

            std::swap(this-&gt;queue_, tmp); // specialized ptr swap
            return result; // return value optimization
        }

    private:
        struct reversed_compare : Compare {
            // notice that all four versions are required
            // so that no new restrictions are created:
            // (you might even want mixed const params..)

            bool operator() (const T&amp; l, const T &amp;r) {
                return Compare::operator()(r, l);
            }

            bool operator() (const T&amp; l, const T&amp; r) const {
                return Compare::operator()(r, l);
            }

            bool operator() (T&amp; l, T&amp; r) {
                return Compare::operator()(r, l);
            }

            bool operator() (T&amp; l, T&amp; r) const {
                return Compare::operator()(r, l);
            }
        };

        std::priority_queue&lt;T, Container, reversed_compare&gt; queue_;
        size_type maxsize_; // not const to stay assignable
};</pre>
<p>Note that the interface for such a class is tricky &#8211; there is no good way of defining the top() functionality, as a maximum heap (with the reversed comparison, mind you) will not let you access the minimal member. It will only give access to the maximal one.<br />
The solution I have suggested here works around this issue by providing only a way for retrieving all elements altogether, through pop_all. I would greatly appreciate any feedback on this matter.</p>
<p>Another interesting property of the pop_all implementation offered here is that it provides a strong <a href="http://en.wikipedia.org/wiki/Exception_guarantees">exception guarantee</a> &#8211; in the case of an exception during the copying of the elements, it will leave the original queue untouched. This is also achieved through the invocation of the <a href="http://www.sgi.com/tech/stl/swap.html">swap</a> algorithm, which should have a (no-throw) pointer-swapping specialization for the underlying vector type.<br />
This is a very important characteristic, and it comes with a cost of an extra copy operation.</p>
<p>One more issue worth taking note of is that the provided pop_all implementation supports <a href="http://en.wikipedia.org/wiki/Return_value_optimization">return value optimization</a>. But that is a topic for another post.</p>
]]></content:encoded>
			<wfw:commentRss>http://efesx.com/2012/04/30/bounded-size-priority-queue/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Imitation of Java Generics</title>
		<link>http://efesx.com/2010/12/31/imitation-of-java-generics/</link>
		<comments>http://efesx.com/2010/12/31/imitation-of-java-generics/#comments</comments>
		<pubDate>Fri, 31 Dec 2010 21:09:48 +0000</pubDate>
		<dc:creator>rmn</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Boost]]></category>
		<category><![CDATA[C++0x]]></category>
		<category><![CDATA[Metaprogramming]]></category>
		<category><![CDATA[Templates]]></category>

		<guid isPermaLink="false">http://cplusplus.co.il/?p=1094</guid>
		<description><![CDATA[Generic programming is very common and has different names (and features) in various programming languages; C++ provides Turing-Complete Templates, Java offers Generics (along with Ada, Eiffel, C#, and Visual Basic .Net), and Parametric Polymorphism is present in ML, Scala, and Haskell. While I am generally pretty happy with what C++ has to offer, adopting some [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Generic_programming">Generic programming</a> is very common and has different names (and features) in various programming languages; C++ provides <a href="http://stackoverflow.com/questions/189172/c-templates-turing-complete">Turing-Complete Templates</a>, Java offers <a href="http://en.wikipedia.org/wiki/Generics_in_Java">Generics</a> (along with Ada, Eiffel, C#, and Visual Basic .Net), and <a href="http://en.wikipedia.org/wiki/Parametric_polymorphism#Parametric_polymorphism">Parametric Polymorphism</a> is present in ML, Scala, and Haskell.</p>
<p>While I am generally pretty happy with what C++ has to offer, adopting some of the features offered by other mechanisms can come in handy sometimes. To be more specific, in this post we will mimic Java&#8217;s support for defining a common super-type for generic elements (i.e. List<T extends Comparable>).</p>
<p><span id="more-1094"></span>The task at hand is the implementation of a priority queue, which is essentially a <a href="http://en.wikipedia.org/wiki/Heap_%28data_structure%29">heap</a>. Sure enough, the priority queue will have a parametric (template) type T, which will have to be Comparable. Something along the lines of:</p>
<pre class="brush: cpp; title: ; notranslate">
template &lt;typename T&gt;
struct priority_queue {
    // ...
};
</pre>
<p>Keep in mind that we will have to do one of two things:</p>
<ul>
<li>Either clearly state in the documentation that the implementation of our priority_queue heavily relies on type T having implemented operator<,</li>
<li>Or add another parametric (template) type F, to serve as a Comparator.</li>
</ul>
<p>Both things may seem a little far from optimal. Have we gone with Java in the first place, all we would have had to do would have been something closely resembling the following:</p>
<pre class="brush: java; title: ; notranslate">
class priority_queue&lt;T extends Comparable&gt;
</pre>
<p>As it turns out, the same effect (although with slightly different syntax) can actually be achieved even in C++, through utilization of two boost utilities: <a href="http://www.boost.org/doc/libs/1_45_0/libs/type_traits/doc/html/boost_typetraits/reference/is_base_of.html">is_base_of</a> and <a href="http://www.boost.org/doc/libs/1_45_0/doc/html/boost_staticassert.html">static_assert</a>. A brief sketch is hereby presented:</p>
<pre class="brush: cpp; title: ; notranslate">
struct Comparable {
    // required API..
};

template &lt;typename T&gt;
class priority_queue {
    // Ask compiler to enforce that T is a subtype of Comparable:
    BOOST_STATIC_ASSERT(boost::is_base_of&lt;Comparable, T&gt;::value);
};
</pre>
<p>A colleague of mine walked up to me some time ago and asked why isn&#8217;t such a mechanism included in C++&#8217;s core features. After putting some more thought into it, I have come to the conclusion that I would actually hate seeing such a built-in C++ feature &#8211; In my opinion, it will lead to an excessive number of not-general-enough base classes, which are only there to feed this mechanism. Moreover, it is very likely to lead to much more abuse of the multiple inheritance mechanism.</p>
<p>The <a href="http://en.wikipedia.org/wiki/C%2B%2B0x">C++0x</a> standard draft presented a related feature named <a href="http://en.wikipedia.org/wiki/Concepts_%28C%2B%2B%29">Concepts</a> (and Concept-maps), which were recently dropped as well.</p>
<p>What do you think?</p>
]]></content:encoded>
			<wfw:commentRss>http://efesx.com/2010/12/31/imitation-of-java-generics/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Exceptional initialization list</title>
		<link>http://efesx.com/2010/11/30/exceptional-initialization-list/</link>
		<comments>http://efesx.com/2010/11/30/exceptional-initialization-list/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 21:32:04 +0000</pubDate>
		<dc:creator>rmn</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[SWIG]]></category>

		<guid isPermaLink="false">http://cplusplus.co.il/?p=1082</guid>
		<description><![CDATA[Using the initialization list is very much encouraged in C++, and rightfully so - it has many benefits. But what happens if one of your members fails at initialization and actually throws an exception? Even worse: what happens if that member&#8217;s constructor throws an exception not in your exception specification list? That&#8217;s what happened to me just [...]]]></description>
			<content:encoded><![CDATA[<p>Using the initialization list is very much encouraged in C++, and rightfully so - it has many benefits. But what happens if one of your members fails at initialization and actually throws an exception? Even worse: what happens if that member&#8217;s constructor throws an exception not in your <a href="http://efesx.com/2009/10/06/exception-specifications/">exception specification list</a>?</p>
<p><span id="more-1082"></span>That&#8217;s what happened to me just the other day; I was using <a href="http://www.swig.org/">SWIG</a> to wrap a C++ class to <a href="http://www.python.org/">Python</a> (by the way, SWIG is just plain awesome), and since exception specification causes wrapping of the exception classes as well, it&#8217;s a good idea to use that. So there I was, declaring my constructor to only throw instances of std::runtime_error.. Only to discover that one of my members (implemented elsewhere) could actually throw a const char*.</p>
<p>Luckily, I was familiar with the idea of catching exceptions raised within the initialization list, and that&#8217;s exactly what was needed to save the day. The required syntax is hereby presented:</p>
<pre class="brush: cpp; title: ; notranslate">
struct myclass {
    myclass () throw(std::runtime_error)
        try
        : m_member(&quot;test&quot;) {
            // normal constructor code
        }
        catch (const char *err) {
            throw std::runtime_error(err);
        }

    private:
        someotherclass m_member;
};
</pre>
<p>There are of course some limitations on what you can do within the catch-block, the major one being that you must throw something; You cannot continue normal execution having failed initializing the object &#8212; if nothing is thrown when reaching the end of the catch-block, the caught exception is automatically re-thrown.</p>
<p>Extra details and more in-depth discussion of the mechanism can be found at <a href="http://www.gotw.ca/gotw/066.htm">GotW#66</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://efesx.com/2010/11/30/exceptional-initialization-list/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Thunksgiving</title>
		<link>http://efesx.com/2010/10/31/thunksgiving/</link>
		<comments>http://efesx.com/2010/10/31/thunksgiving/#comments</comments>
		<pubDate>Sun, 31 Oct 2010 20:59:25 +0000</pubDate>
		<dc:creator>rmn</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[GCC]]></category>
		<category><![CDATA[Lowlevel]]></category>

		<guid isPermaLink="false">http://cplusplus.co.il/?p=1059</guid>
		<description><![CDATA[Quoting Wikipedia: The word thunk has at least three related meanings in computing science. A &#8220;thunk&#8221; may be: A piece of code to perform a delayed computation (similar to a closure) A feature of some virtual function table implementations (similar to a wrapper function) A mapping of machine data from one system-specific form to another, [...]]]></description>
			<content:encoded><![CDATA[<p>Quoting <a href="http://en.wikipedia.org/wiki/Thunk">Wikipedia</a>:</p>
<blockquote><p>The word thunk has at least three related meanings in computing science. A &#8220;thunk&#8221; may be:</p>
<ol>
<li>A piece of code to perform a delayed computation (similar to a closure)</li>
<li>A feature of some virtual function table implementations (similar to a wrapper function)</li>
<li>A mapping of machine data from one system-specific form to another, usually for compatibility reasons</li>
</ol>
<p>In all three senses, the word refers to a piece of low-level code, usually machine-generated, that implements some detail of a particular software system.</p></blockquote>
<p>In this post (whose name looks like an unrelated typo) we shall observe the need for a thunk of the second kind, in C++.</p>
<p><span id="more-1059"></span>Let us consider the following multiple inheritance hierarchy:</p>
<pre class="brush: cpp; title: ; notranslate">
#include &lt;iostream&gt;

struct A {
    virtual A *clone () const {
        return new A();
    }

    int a;
};

struct B {
    virtual B *clone () const {
        return new B();
    }

    int b;
};

struct C : A, B {
    virtual C *clone () const {
        C *c = new C();
        std::cout &lt;&lt; c &lt;&lt; std::endl;
        return c;
    }

    int c;
};

int main () {
    B *b = new C();
    B *b_cloned = b-&gt;clone();
    std::cout &lt;&lt; b_cloned &lt;&lt; std::endl;
}
</pre>
<p>Please, do not let the length of the code snippet intimidate you. The illustrated test case is actually pretty simple; Three classes are defined &#8212; A, B, and C. C is derived from the unrelated other classes. All classes share a single virtual function which allows to clone() them, and a single member variable &#8211; just so they aren&#8217;t empty. The purpose of the two printouts will be made clear soon.</p>
<p>One nuance worth paying attention to is the fact that the clone() function is refined within C::clone() to yield a pointer-to-C instead of pointer-to-A/B. This is called <a href="http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29">Covariance</a>. I could talk a lot more about Covariance, Contravariance, and C++&#8217;s lack of support for Contravariance in function parameters, but these topics will have to wait for a later post.</p>
<p>Let us recap what memory layout do A, B, and C have (on a 32bit machine):<br />
<code><br />
A: [ Avptr | int(a) ] 8bytes<br />
B: [ Bvptr | int(b) ] 8bytes<br />
C: [ Cvptr | int(a) | BCvptr | int(b) | int(c) ] 20bytes<br />
</code></p>
<p>Needless to say that a cast from C* to A* requires no effort at all, while the virtual table pointer (vptr) of class B (notice that it is labeled BCvptr, which is intentionally different from Bvptr) is where it is to allow convenient casts of the form C* to B*. Therefore, it is not surprising to discover that the compiler will actually carry out much needed pointer adjustments in the following case:</p>
<pre class="brush: cpp; title: ; notranslate">
C c;
B *b = &amp;c; // b != &amp;c. Actually, b = &amp;c+8.
</pre>
<p>Now, onwards to the interesting part; What happens when we write line #31 in the original code snippet (invocation of C::clone() which yields a pointer-to-C, from a B context)? And more importantly, what is actually going on under the hood?</p>
<p>The call b->clone() is invoked through the BCvptr. Due to the dynamic type of the object being C, we expect C::clone() to be called. But here&#8217;s the catch &#8212; a call to C::clone() yields a pointer (to a newly constructed C object) which points to the head of a C object, rather than to a B object! If C::clone() would be called normally, we would have a pointer-to-B which points on the wrong memory area, and that would just make us all unhappy.. So what dark magic is there, within BCvptr, that allows this code to work flawlessly?</p>
<p>Using the magical <strong>-fdump-class-hierarchy</strong> flag for <a href="http://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html">g++</a>, and the wondrous <a href="http://www.sourceware.org/binutils/docs-2.16/binutils/c_002b_002bfilt.html">c++filt</a> utility, we can obtain the actual structure of C&#8217;s virtual table:</p>
<p><code><br />
Vtable for C<br />
C::vtable for C: 6u entries<br />
0     (int (*)(...))0<br />
4     (int (*)(...))(&#038; typeinfo for C)<br />
8     C::clone<br />
12    (int (*)(...))-0x00000000000000008<br />
16    (int (*)(...))(&#038; typeinfo for C)<br />
20    C::covariant return thunk to C::clone() const<br />
</code></p>
<p>I will not go into much detail about the whole structure as it is enough information for one post, but I do believe that what&#8217;s important to us is pretty apparent here: at offset 8 there&#8217;s the normal invocation of C::clone within a Cvptr, while at offset 20 (which is exactly 12+8) there&#8217;s a call to a <strong>&#8220;covariant return thunk to C::clone&#8221;</strong>. As you have probably guessed by now, BCvptr is actually a pointer to offset 12 within Cvptr. Therefore, when making the aforementioned b->clone() call &#8212; a call is made to the function whose address resides at offset 8 from the current vptr; And since the current vptr is BCvptr, a call to the thunk is made.</p>
<p>Obviously, the compiler essentially implements this thunk as a simple wrapper around C::clone() combined with the required pointer adjustment to yield a proper pointer-to-B. Some of you may find this technique pretty similar to the notion of a <a href="http://en.wikipedia.org/wiki/Trampoline_%28computers%29">Trampoline</a>.</p>
<p>To wrap things up, it should come as no surprise to you, that both printouts produce addresses which differ by 8bytes &#8212; which is the exact required adjustment.</p>
]]></content:encoded>
			<wfw:commentRss>http://efesx.com/2010/10/31/thunksgiving/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Endianness and you</title>
		<link>http://efesx.com/2010/09/30/endianness-and-you/</link>
		<comments>http://efesx.com/2010/09/30/endianness-and-you/#comments</comments>
		<pubDate>Thu, 30 Sep 2010 21:32:50 +0000</pubDate>
		<dc:creator>rmn</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Lowlevel]]></category>

		<guid isPermaLink="false">http://cplusplus.co.il/?p=1043</guid>
		<description><![CDATA[Programming is all about generalizations. We, as programmers, usually do not want to worry about all the small details; We will usually assume that there&#8217;s enough physical memory on the machine, we will knowingly use cross-platform libraries to make the operating system we&#8217;re running on irrelevant as well, and sometimes we will even resort to [...]]]></description>
			<content:encoded><![CDATA[<p>Programming is all about generalizations. We, as programmers, usually do not want to worry about all the small details; We will usually assume that there&#8217;s enough physical memory on the machine, we will knowingly use cross-platform libraries to make the operating system we&#8217;re running on irrelevant as well, and sometimes we will even resort to using programming languages that take these ideas to the extreme &#8211; like i.e. <a href="http://en.wikipedia.org/wiki/Java_%28programming_language%29">Java</a>, which runs entirely on a virtual machine &#8212; making all above issues non-existent.</p>
<p>But there comes a time, especially in low-level programming languages (like C++ luckily is), when we simply cannot ignore certain low level details. One such example is the expected, architecture specific, <a href="http://en.wikipedia.org/wiki/Endianness">Endianness</a>.</p>
<p><span id="more-1043"></span>Quoting Wikipedia:</p>
<blockquote><p>Endianness is the ordering of individually addressable sub-units (words, bytes, or even bits) within a longer data word stored in external memory.</p></blockquote>
<p>To be more specific, usually what concerns us is the byte ordering (since every byte is individually addressable in the common <a href="http://en.wikipedia.org/wiki/X86">x86/IA32 architecture</a>) within a bigger word, such as a 32bit integer (4bytes). There are essentially two &#8220;core&#8221; options:</p>
<ul>
<li>Little Endian &#8212; Little (less significant) byte first.</li>
<li>Big Endian &#8212; Big (most significant) byte first.</li>
</ul>
<p>Little Endian, in my opinion, is the less intuitive one. It means that if we are to store a 32bit integer of the <a href="http://en.wikipedia.org/wiki/Hexadecimal">Hexadecimal</a> value 0&#215;10203040 in memory address a, then the memory footprint would look like this: [40 30 20 10], where a[0]=40 a[1]=30 a[2]=20 a[3]=10.</p>
<p>Most PCs are of the x86 architecture. As such, you are very likely to bump into the Little Endian storage it employs. Here is a simple program illustrating the situation:</p>
<pre class="brush: cpp; title: ; notranslate">
#include &lt;iostream&gt;

int main () {
    int integer = 0x10203040;
    char *ptr   = static_cast&lt;char*&gt;(static_cast&lt;void*&gt;(&amp;integer));

    std::cout &lt;&lt; &quot;int:   &quot; &lt;&lt; std::hex &lt;&lt; integer
        &lt;&lt; std::endl;
    std::cout &lt;&lt; &quot;int[0]:&quot; &lt;&lt; std::hex &lt;&lt; static_cast&lt;int&gt;(ptr[0])
        &lt;&lt; std::endl;

    if (ptr[0] == (integer&amp;0xff))
        std::cout &lt;&lt; &quot;little endian detected&quot; &lt;&lt; std::endl;
    else
        std::cout &lt;&lt; &quot;big endian detected&quot; &lt;&lt; std::endl;
}
</pre>
<p>As expected, on my Intel Pentium M, the output would be:</p>
<blockquote><p>antrikot:~/work/sandbox> ./endianness-test<br />
int:   10203040<br />
int[0]:40<br />
little endian detected</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://efesx.com/2010/09/30/endianness-and-you/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Overloading macros</title>
		<link>http://efesx.com/2010/08/31/overloading-macros/</link>
		<comments>http://efesx.com/2010/08/31/overloading-macros/#comments</comments>
		<pubDate>Tue, 31 Aug 2010 19:44:22 +0000</pubDate>
		<dc:creator>rmn</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Metaprogramming]]></category>

		<guid isPermaLink="false">http://cplusplus.co.il/?p=1028</guid>
		<description><![CDATA[The feature of function overloading can prove to be pretty useful: it allows us to define a few versions of the same function, which differ in argument types, or even in Arity (ignoring variadic functions for the moment). Unfortunately, the C\C++ pre-processor does not allow overloading macros in the same way; It treats such attempts [...]]]></description>
			<content:encoded><![CDATA[<p>The feature of <a href="http://en.wikipedia.org/wiki/Function_overloading">function overloading</a> can prove to be pretty useful: it allows us to define a few versions of the same function, which differ in argument types, or even in <a href="http://en.wikipedia.org/wiki/Arity">Arity</a> (ignoring <a href="http://en.wikipedia.org/wiki/Variadic_function">variadic functions</a> for the moment). Unfortunately, the C\C++ pre-processor does not allow overloading macros in the same way; It treats such attempts as redefinitions.</p>
<p>While we do not really need to overload a macro in order to handle different argument types (since macros ignore type information), many times it would be desired to overload a macro such that each version is able to handle a different number of arguments. This goal can actually be achieved through invocation of the VA_NUM_ARGS macro mentioned in my <a href="http://efesx.com/2010/07/17/variadic-macro-to-count-number-of-arguments/">previous post</a>, as we will briefly demonstrate (the idea has also been mentioned under the comment section in the aforementioned post).</p>
<p><span id="more-1028"></span>Suppose we would like to create a macro which is to return the MAX of its arguments. Such feature is supported both by <a href="http://www.cplusplus.com/reference/algorithm/max/">std::max</a> and by the (in)famous <a href="http://www.faqs.org/docs/learnc/x843.html">MAX macro</a>. The extra requirement we shall make here, other than insisting on a macro solution, is that the implementation should work for any positive number of arguments up to a certain limit, and as long as there&#8217;s at least one argument.</p>
<p>In this post we will provide a solution which computes the MAX of up to three arguments, but we will put an emphasis on providing a solution which is easy to scale to work with any number of arguments.</p>
<p>One approach, cleverly raised by a colleague of mine, suggests the following (example supporting up to three arguments):</p>
<pre class="brush: cpp; title: ; notranslate">
#define MAX2(a, b) (((a)&gt;(b)) ? (a) : (b))

#define MAX(a, ...) MAX_IMPL(a, __VA_ARGS__, a, a)
#define MAX_IMPL(a, b, c, ...) MAX2(a, MAX2(b, c))
</pre>
<p>This should clearly work for the MAX macro we are after, but certainly not for every function we would like to implement; For instance, if we were after a macro which can compute the average of its arguments, this approach would clearly not work.</p>
<p>The generic solution for macro overloading, and specifically for our case, is by employing the VA_NUM_ARGS construct with the following set of macros:</p>
<pre class="brush: cpp; title: ; notranslate">
#define macro_dispatcher(func, ...) \
            macro_dispatcher_(func, VA_NUM_ARGS(__VA_ARGS__))
#define macro_dispatcher_(func, nargs) \
            macro_dispatcher__(func, nargs)
#define macro_dispatcher__(func, nargs) \
            func ## nargs
</pre>
<p>The macro_dispatcher mechanism actually implements, like its name suggests, a kind of a dispatch mechanism (which operates through calculating the number of arguments being passed to the macro) that is actually able to simulate an overloading mechanism. Thus, enabling the following implementation for our desired max macro:</p>
<pre class="brush: cpp; title: ; notranslate">
#define max(...) macro_dispatcher(max, __VA_ARGS__)(__VA_ARGS__)

#define max1(a) a
#define max2(a, b) ((a)&gt;(b)?(a):(b))
#define max3(a, b, c) max2(max2(a, b), c)
// ...

// to verify, run the preprocessor alone (g++ -E):
max(1, 2, 3);
</pre>
<p>In this scenario, the macro_dispatcher mechanism transforms the max(1, 2, 3) call to max3(1, 2, 3) invocation, which yields the desired result.</p>
<p>Needless to say, that the proposed technique can be utilized easily just about anywhere where macro overloading would be useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://efesx.com/2010/08/31/overloading-macros/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Variadic macro to count number of arguments</title>
		<link>http://efesx.com/2010/07/17/variadic-macro-to-count-number-of-arguments/</link>
		<comments>http://efesx.com/2010/07/17/variadic-macro-to-count-number-of-arguments/#comments</comments>
		<pubDate>Sat, 17 Jul 2010 09:20:34 +0000</pubDate>
		<dc:creator>rmn</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Metaprogramming]]></category>

		<guid isPermaLink="false">http://cplusplus.co.il/?p=1003</guid>
		<description><![CDATA[The C-Preprocessor is a very powerful mechanism, which offers many different features. One of these features is called Variadic macros: macros that accept a varying number of arguments. It is interesting to note at this point, that such Variadic macros, despite being part of the C99 Standard, are not part of the C++ Standard at [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://en.wikipedia.org/wiki/C_preprocessor">C-Preprocessor</a> is a very powerful mechanism, which offers many different features. One of these features is called <a href="http://en.wikipedia.org/wiki/Variadic_macro">Variadic macros</a>: macros that accept a varying number of arguments. It is interesting to note at this point, that such Variadic macros, despite being part of the C99 Standard, are not part of the C++ Standard at the moment. However, a big number of C++ compilers support it nevertheless.</p>
<p>While allowing the definition of Variadic macros, there is no built-in (preprocessor) way of obtaining the actual number of arguments that is passed to a specific Variadic macro. In this post we shall provide a possible macro implementation for such a query.</p>
<p><span id="more-1003"></span>Let us first present the solution (which has also been proposed <a href="http://groups.google.com/group/comp.std.c/browse_thread/thread/77ee8c8f92e4a3fb/346fc464319b1ee5?pli=1">before</a>), and then we shall move on to discuss how it works and its limitations;</p>
<pre class="brush: cpp; title: ; notranslate">
#define VA_NUM_ARGS(...) VA_NUM_ARGS_IMPL(__VA_ARGS__, 5,4,3,2,1)
#define VA_NUM_ARGS_IMPL(_1,_2,_3,_4,_5,N,...) N

// to verify, run the preprocessor alone (g++ -E):
VA_NUM_ARGS(x,y,z)
</pre>
<p>As with every Variadic macro, __VA_ARGS__ is replaced with the passed arguments, therefore making a little &#8220;shift&#8221; in the arguments following it. Thus, when we check the arguments being passed to VA_NUM_ARGS_IMPL, the aforementioned &#8220;shift&#8221; causes the sixth argument to hold the right &#8211; initial &#8211; number of arguments.</p>
<p>The given implementation imposes a couple of limitations:</p>
<ul>
<li><i>It will not work correctly for zero arguments.</i> Some suggestions for an implementation capable of supporting this feature can be found in the comments section below.</li>
<li><i>It supports only a limited number of arguments (up to 5, to be precise).</i> The macro can be extended to support a maximal number of up to 63 arguments (in a way that is pretty obvious), which seems to push the upper bound for number of preprocessor macro arguments any way.</li>
</ul>
<p>Can you propose a case where this would be useful? I am planning to share a number of ideas in future posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://efesx.com/2010/07/17/variadic-macro-to-count-number-of-arguments/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Futures: asynchronous invocation</title>
		<link>http://efesx.com/2010/05/31/futures-asynchronous-invocation/</link>
		<comments>http://efesx.com/2010/05/31/futures-asynchronous-invocation/#comments</comments>
		<pubDate>Sun, 30 May 2010 21:01:34 +0000</pubDate>
		<dc:creator>rmn</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Boost]]></category>
		<category><![CDATA[C++0x]]></category>
		<category><![CDATA[Concurrency]]></category>

		<guid isPermaLink="false">http://cplusplus.co.il/?p=987</guid>
		<description><![CDATA[In the concurrent world, a Future object refers to an object whose actual value is to be computed in the future. You can think of it as a handle to an asynchronous invocation of a computation that yields a value. Many so called concurrent programming languages support this idea as a native construct offered by [...]]]></description>
			<content:encoded><![CDATA[<p>In the concurrent world, a <a href="http://en.wikipedia.org/wiki/Futures_and_promises">Future object</a> refers to an object whose actual value is to be computed in the future. You can think of it as a handle to an asynchronous invocation of a computation that yields a value.</p>
<p>Many so called concurrent programming languages support this idea as a native construct offered by the core language itself. Unfortunately, C++ does not. Well, at least not in the current standard; C++0x (or shall I say C++1x ?) is going to support <a href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-8-futures-and-promises.html">std::future</a> as part of the massive new C++0x thread library, which is based on <a href="http://www.boost.org/doc/libs/1_43_0/doc/html/thread.html">boost::thread</a>. In this post we will implement a simple, yet very powerful, such future object.</p>
<p><span id="more-987"></span>As you could guess, our future object will create its own thread of execution in order to carry out the needed asynchronous computation. We shall exploit boost::thread for this task. A straightforward implementation is hereby presented:</p>
<pre class="brush: cpp; title: ; notranslate">#ifndef _FUTURE_HPP_
#define _FUTURE_HPP_

#include &lt;boost/utility.hpp&gt;
#include &lt;boost/thread.hpp&gt;
#include &lt;tr1/functional&gt;

namespace std { using namespace std::tr1; }

template &lt;typename T&gt;
class future : boost::noncopyable {
    public:
        future (const std::function&lt;T ()&gt; &amp;func);
        operator T&amp; ();
        bool ready () const;

    private:
        void compute ();

        volatile bool ready_, joined_;
        std::function&lt;T ()&gt; func_;
        boost::mutex mutex_;
        T result_;

        boost::thread thread_;
};

template &lt;typename T&gt;
future&lt;T&gt;::future (const std::function&lt;T ()&gt; &amp;func)
 : ready_(false), joined_(false), func_(func),
   thread_(boost::bind(&amp;future::compute, this))
{ }

template &lt;typename T&gt;
future&lt;T&gt;::operator T&amp; () {
    if (!joined_) {
        // locking to prevent race conditions on join() which causes
        // undefined behavior if called more than once.
        // using double checked locking with all of its downsides.
        boost::mutex::scoped_lock lock(mutex_);
        if (!joined_) {
            thread_.join();
            joined_ = true;
        }
    }
    return result_;
}

template &lt;typename T&gt;
bool future&lt;T&gt;::ready () const {
    return ready_;
}

template &lt;typename T&gt;
void future&lt;T&gt;::compute () {
    result_ = func_();
    ready_ = true;
}

#endif // _FUTURE_HPP_</pre>
<p>Few points worth taking note of in this implementation are these:</p>
<ul>
<li>We have to use a mutex to prevent a race condition on the join() operation, which may cause <a href="http://lists.boost.org/Archives/boost/2001/08/16762.php">undefined behavior if called more than once</a> and is not thread safe.</li>
<li>Double checked locking is problematic in many cases (I strongly suggest reading this <a href="http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf">article</a> about &#8220;C++ and the Perils of Double-Checked Locking&#8221; by Alexandrescu and Meyers) but should be fine here.</li>
<li>The use of <a href="http://www.devx.com/cplus/10MinuteSolution/32455">std::tr1::function</a> and <a href="http://www.boost.org/doc/libs/1_43_0/libs/bind/bind.html">boost::bind</a> (<a href="http://www.drdobbs.com/architecture-and-design/184401949">also in tr1</a>) greatly simplify the implementation and its interface.</li>
</ul>
<p>It is also important to mention that the folks at boost provide <a href="http://www.boost.org/doc/libs/1_42_0/doc/html/thread/synchronization.html#thread.synchronization.futures">a similar functionality</a> as part of boost::thread, but the interface seems a little uncomfortable. At least to me.</p>
<p>Now, a utilization example is in order. How would you feel about <a href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci numbers</a> making another appearance?</p>
<pre class="brush: cpp; title: ; notranslate">#include &lt;iostream&gt;
#include &lt;tr1/tuple&gt;
#include &lt;boost/bind.hpp&gt;

#include &quot;future.hpp&quot;

namespace std { using namespace std::tr1; }

unsigned nth_fib (unsigned n, unsigned modulo) {
    unsigned prev=1, curr=1;
    for (unsigned c=2;c&lt;n;++c)
        std::tie(prev, curr) =
            std::make_tuple(curr, (prev+curr) % modulo);
    return curr;
}

int main () {
    future&lt;unsigned&gt; fib1(boost::bind(nth_fib, 1000000, 4567)),
                     fib2(boost::bind(nth_fib, 3000000, 1234));

    while (!fib1.ready() || !fib2.ready()) {
        std::cout &lt;&lt; &quot;working..&quot; &lt;&lt; std::endl;
        boost::this_thread::sleep(boost::posix_time::seconds(1));
    }

    std::cout &lt;&lt; &quot;fib1: &quot; &lt;&lt; fib1 &lt;&lt; &quot; fib2: &quot; &lt;&lt; fib2 &lt;&lt; std::endl;
}</pre>
<p>Just a reminder: <a href="http://efesx.com/2010/01/15/tuples/">using Tuples is pretty efficient</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://efesx.com/2010/05/31/futures-asynchronous-invocation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Catching uncaught exceptions within terminate</title>
		<link>http://efesx.com/2010/03/21/catching-uncaught-exceptions-within-terminate/</link>
		<comments>http://efesx.com/2010/03/21/catching-uncaught-exceptions-within-terminate/#comments</comments>
		<pubDate>Sat, 20 Mar 2010 22:41:05 +0000</pubDate>
		<dc:creator>rmn</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[GCC]]></category>
		<category><![CDATA[VisualStudio]]></category>

		<guid isPermaLink="false">http://cplusplus.co.il/?p=625</guid>
		<description><![CDATA[The handler std::terminate() is called whenever the exception handling mechanism cannot find a suitable catch clause for a thrown exception (and in some other cases. For example, when an exception is thrown during the handling of another exception &#8211; see this GotW post about std::uncaught_exception). It is possible to define a custom handler by using [...]]]></description>
			<content:encoded><![CDATA[<p>The handler std::terminate() is called whenever the exception handling mechanism cannot find a suitable catch clause for a thrown exception (and in some other cases. For example, when an exception is thrown during the handling of another exception &#8211; see <a href="http://www.gotw.ca/gotw/047.htm">this GotW post</a> about std::uncaught_exception). It is possible to define a custom handler by using <a href="http://www.cplusplus.com/reference/std/exception/set_terminate/">std::set_terminate</a>.</p>
<p>In this post we would like to create a terminate handler which will be able to catch the exception that led to its invocation, when there is one.</p>
<p><span id="more-625"></span>Consider the following main function:</p>
<pre class="brush: cpp; title: ; notranslate">#include &lt;stdexcept&gt;

int main () {
    throw std::runtime_error(&quot;error!&quot;);
}</pre>
<p>Now, let us create our own terminate handler, which we will call &#8216;our_terminate&#8217;. We will use a trick to configure it even before the main function gets to run, by invoking set_handler as part of a global constant initialization (be aware of the <a href="http://www-d0.fnal.gov/KAI/doc/tutorials/static_initialization.html">random initialization order</a> of global objects):</p>
<pre class="brush: cpp; title: ; notranslate">#include &lt;exception&gt;

void our_terminate (void); // decleration

namespace {
    static const bool SET_TERMINATE =
        std::set_terminate(our_terminate);
}</pre>
<p>At this point, we are left with the challenge of writing the actual terminate handler we&#8217;re after. As far as I know there is no portable solution. The solution we will present here works for GCC (verified on versions 3.* and 4.*). It does not seem to work on Microsoft&#8217;s Visual Studio (2008), so a different approach should be taken there. It is always possible to check where the compiler places the currently active exception, and just take it from there (thus providing a compiler specific workaround for every compiler). Feel free to comment on the matter.</p>
<p>Normally, an empty throw directive (&#8216;throw;&#8217;) outside of a catch clause (&#8216;throw;&#8217; within a catch clause means a re-throw of the caught exception) would lead to the invocation of the terminate handler. The interesting thing however, is that under GCC, using such an empty throw statement within our custom terminate handler will cause a re-throw of the currently active exception (if there is one), making the following code behave as desired:</p>
<pre class="brush: cpp; title: ; notranslate">#include &lt;iostream&gt;

void our_terminate (void) { // try 1
    try { throw; }
    catch (const std::runtime_error &amp;err) {
        std::cout &lt;&lt; &quot;caught a runtime_error. what(): &quot; &lt;&lt;
            err.what() &lt;&lt; std::endl;
    }
    catch (...) {
        std::cout &lt;&lt; &quot;unknown exception occurred.&quot; &lt;&lt;
            std::endl;
    }
}</pre>
<p>That actually works, for the reasons specified above. But this solution is far from being complete; What if an empty throw directive led to the invocation of our custom terminate handler?</p>
<pre class="brush: cpp; title: ; notranslate">int main () {
    throw;
}</pre>
<p>There is no active exception, so the empty throw statement is actually executed in an endless loop (by repeatedly re-invoking the terminate handler, until the stack is exhausted).</p>
<p>So we would like to invoke &#8216;throw;&#8217; only once. A possible solution is this:</p>
<pre class="brush: cpp; title: ; notranslate">void our_terminate (void) { // try 2
    static bool tried_throw = false;

    try {
        if (!tried_throw++) throw;
        std::cout &lt;&lt; &quot;no active exception&quot; &lt;&lt; std::endl;
    }
    catch (const std::runtime_error &amp;err) {
        std::cout &lt;&lt; &quot;caught a runtime_error. what(): &quot; &lt;&lt;
            err.what() &lt;&lt; std::endl;
    }
    catch (...) {
        std::cout &lt;&lt; &quot;unknown exception occurred.&quot; &lt;&lt;
            std::endl;
    }
}</pre>
<p>The empty throw will not be attempted the second time around, making this solution work as expected &#8211; even for the case where there is no pending exception.</p>
<p>In case the terminate handler is likely to be invoked more than once in your own environment, I would recommend resetting the &#8216;tried_throw&#8217; flag back to false after printing the proper message.</p>
]]></content:encoded>
			<wfw:commentRss>http://efesx.com/2010/03/21/catching-uncaught-exceptions-within-terminate/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Escaping overloaded operators</title>
		<link>http://efesx.com/2010/02/19/escaping-overloaded-operators/</link>
		<comments>http://efesx.com/2010/02/19/escaping-overloaded-operators/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 11:54:36 +0000</pubDate>
		<dc:creator>rmn</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Boost]]></category>

		<guid isPermaLink="false">http://cplusplus.co.il/?p=892</guid>
		<description><![CDATA[The possibility of overloading just about any C++ operator and having it do something entirely different from what it was designed for, can sometimes make life pretty hard. Here are a couple of examples: What if you wanted to take the address of an object, which had implemented an entirely different semantic for the ampersand [...]]]></description>
			<content:encoded><![CDATA[<p>The possibility of <a href="http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr318.htm">overloading just about any C++ operator</a> and having it do something entirely different from what it was designed for, can sometimes make life pretty hard.</p>
<p>Here are a couple of examples: What if you wanted to take the address of an object, which had implemented an entirely different semantic for the ampersand (&#038;) operator? Or what if somebody decided to overload the comma operator in some strange manner?</p>
<p>As you could have guessed, there are solutions for such scenarios.</p>
<p><span id="more-892"></span><strong>The comma operator (operator,)</strong></p>
<p>Suppose there&#8217;s some sequence object, which you would want to advance and then print:</p>
<pre class="brush: cpp; title: ; notranslate">#include &lt;iostream&gt;

template &lt;typename T&gt;
void print_seq (const T &amp;seq) {
    seq.reset();
    for (unsigned i=0;i&lt;seq.size();seq.advance(), ++i)
        std::cout &lt;&lt; i &lt;&lt; &quot; &quot; &lt;&lt; seq.curr() &lt;&lt; std::endl;
}</pre>
<p>Everything looks peachy until now, right? Well, not exactly;</p>
<pre class="brush: cpp; title: ; notranslate">struct sequence {
        sequence &amp;reset   ()       { return *this; }
        sequence &amp;advance ()       { return *this; }
        size_t    size    () const { return 0;     }
        unsigned  curr    () const { return 0;     }
    private:
        void operator, (unsigned)  {  /* none. */  }
};

int main () {
    // this will complain about comma operator being private!
    sequence seq;
    print_seq(seq);
}</pre>
<p>What we&#8217;ve witnessed just now is that writing generic functions (or libraries), like our templated &#8216;print_seq&#8217; function, can be a little tricky when the unexpected strikes. Luckily, there&#8217;s a solution: we are able to invoke the &#8216;void()&#8217; token to keep user-defined overloaded comma operators from running. Here&#8217;s how we should re-write the function:</p>
<pre class="brush: cpp; title: ; notranslate">template &lt;typename T&gt;
void print_seq (T &amp;seq) {
    seq.reset();
    for (unsigned i=0;i&lt;seq.size();seq.advance(), void(), ++i)
        std::cout &lt;&lt; i &lt;&lt; &quot; &quot; &lt;&lt; seq.curr() &lt;&lt; std::endl;
}</pre>
<p>Using &#8216;void()&#8217; we make sure that only the default comma operator gets to execute, instead of any user defined ones (in case there are any).</p>
<p>Now we shall discuss another operator which can be overloaded in many unexpected ways;</p>
<p><strong>The ampersand operator (operator&#038;), also known as &#8216;address of&#8217;</strong></p>
<p>Assume the task at hand is to write a generic improvement of an equality test, such that it would first check if both operands are the same object (by comparing their addresses) and only then invoke operator== for the actual comparison:</p>
<pre class="brush: cpp; title: ; notranslate">template &lt;typename T&gt;
bool equal (const T &amp;lh, const T &amp;rh) {
    return &amp;lh == &amp;rh || lh == rh;
}</pre>
<p>C++&#8217;s <a href="http://en.wikipedia.org/wiki/Short-circuit_evaluation">short-circuit evaluation mechanism</a> guarantees that if the first comparison is successful, the second one (which is usually more expensive) will not be invoked.</p>
<p>Being familiar with the first example in this post, your spider senses must be going off at this point. You should be asking yourself: &#8220;What if T has an overloaded user-defined version of operator&#038;?&#8221;. Indeed, let me illustrate such a case:</p>
<pre class="brush: cpp; title: ; notranslate">template &lt;typename T&gt;
struct vector_element {
    unsigned operator&amp; () const { return idx_; }
    // .. rest of implementation ..
};</pre>
<p>The &#8216;vector_element&#8217; class represents an element of a vector. As such, its operator&#038; simply returns its index in the vector. So if we have two such vectors, and we attempt to compare two of their elements using the proposed &#8216;equal&#8217; function, the result is going to be wrong. For example:</p>
<pre class="brush: cpp; title: ; notranslate">std::vector&lt;vector_element&lt;unsigned&gt; &gt; v1, v2;
// ...
if (equal(v1[5], v2[5]))
    std::cout &lt;&lt; &quot;Always true, regardless of value.&quot; &lt;&lt; std::endl;</pre>
<p>So how could we avoid this situation, you ask?</p>
<p>Well, the folks at boost have implemented a <a href="http://www.boost.org/doc/libs/1_42_0/libs/utility/utility.htm#addressof">boost::addressof()</a> utility function, which I strongly suggest you use in case of need. For the sake of completeness, here&#8217;s how we would implement such a functionality ourselves:</p>
<pre class="brush: cpp; title: ; notranslate">template &lt;class T&gt;
inline T* addressof (T &amp;val) {
    return reinterpret_cast&lt;T*&gt;(
        &amp;const_cast&lt;char&amp;&gt;(reinterpret_cast&lt;const char&amp;&gt;(val)));
}</pre>
<p>A couple of key points are worth noting here:</p>
<ul>
<li>The const cast is useful since it saves us from the need of providing another overload for the const T&#038; case.</li>
<li>This implementation is well defined and portable since we&#8217;re reinterpret-casting from T to A, and then vice versa. (A being a char type here, but we could have used a local class, or something else, just as easily).</li>
</ul>
<p>The boost implementation has some extra minor tweaks, but is essentially the same.</p>
<p>With this implementation, we would be able to provide a correct version of the &#8216;equal&#8217; functionality we were so eager to achieve:</p>
<pre class="brush: cpp; title: ; notranslate">template &lt;typename T&gt;
bool equal (const T &amp;lh, const T &amp;rh) {
    return addressof(lh) == addressof(rh) || lh == rh;
}</pre>
<p>I hope that this post illustrates just how careful we must be when implementing very generic solutions, and that it is quite possible to overcome just about any obstacle &#8211; as long as we can foresee it.</p>
]]></content:encoded>
			<wfw:commentRss>http://efesx.com/2010/02/19/escaping-overloaded-operators/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

