Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Another way to do that is through <a href="http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="nofollow">CRTP</a> and operator overloading helpers (Like <a href="http://www.boost.org/doc/libs/1_53_0/libs/utility/operators.htm" rel="nofollow">boost operators header</a>)</p> <p>Suposse you have the following helper:</p> <pre><code>template&lt;typename T&gt; struct AddHelper { T&amp; operator++() { T&amp; reference = static_cast&lt;T&amp;&gt;(*this); reference.add(); return reference; } T operator++(int) { AddHelper&lt;T&gt; copy( *this ); operator++(); return static_cast&lt;T&gt;(copy); } }; </code></pre> <p>The <strong>add()</strong> implementation is provided by the base class:</p> <pre><code>class Vehicle { private: int _n; public: void add(int n) { _n += n; } ... }; </code></pre> <p>Because <code>Vehicle::add()</code> is public, we can use it in every Vehicle subclasses, thats means you can have <strong>specific operator++ for every Vehicle subclasses</strong> thanks to AddHelper:</p> <pre><code>class Car : public Vehicle , public AddHelper&lt;Car&gt; { Car(int n) : Vehicle(n) {} ... }; class Motorcicle : public Vehicle , public AddHelper&lt;Motorcicle&gt; { Motorcicle(int n) : Vehicle(n) {} ... }; class Bus : public Vehicle , public AddHelper&lt;Bus&gt; { Bus(int n) : Vehicle(n) {} ... }; ... //Ad infinitum </code></pre> <p>Another advantage of this way is that it doesnt use virtual functions to provide the polymorphism, so its more efficient (Static polymorphism instead of dynamic polymorphism).</p>
    singulars
    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.
    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