Note that there are some explanatory texts on larger screens.

plurals
  1. POClass template specializations with shared functionality
    text
    copied!<p>I'm writing a simple maths library with a template vector type:</p> <pre><code>template&lt;typename T, size_t N&gt; class Vector { public: Vector&lt;T, N&gt; &amp;operator+=(Vector&lt;T, N&gt; const &amp;other); // ... more operators, functions ... }; </code></pre> <p>Now I want some <em>additional</em> functionality specifically for some of these. Let's say I want functions <code>x()</code> and <code>y()</code> on <code>Vector&lt;T, 2&gt;</code> to access particular coordinates. I could create a partial specialization for this:</p> <pre><code>template&lt;typename T&gt; class Vector&lt;T, 3&gt; { public: Vector&lt;T, 3&gt; &amp;operator+=(Vector&lt;T, 3&gt; const &amp;other); // ... and again all the operators and functions ... T x() const; T y() const; }; </code></pre> <p>But now I'm repeating everything that already existed in the generic template.</p> <p>I could also use inheritance. Renaming the generic template to <code>VectorBase</code>, I could do this:</p> <pre><code>template&lt;typename T, size_t N&gt; class Vector : public VectorBase&lt;T, N&gt; { }; template&lt;typename T&gt; class Vector&lt;T, 3&gt; : public VectorBase&lt;T, 3&gt; { public: T x() const; T y() const; }; </code></pre> <p>However, now the problem is that all operators are defined on <code>VectorBase</code>, so they return <code>VectorBase</code> instances. These cannot be assigned to <code>Vector</code> variables:</p> <pre><code>Vector&lt;float, 3&gt; v; Vector&lt;float, 3&gt; w; w = 5 * v; // error: no conversion from VectorBase&lt;float, 3&gt; to Vector&lt;float, 3&gt; </code></pre> <p>I could give <code>Vector</code> an implicit conversion constructor to make this possible:</p> <pre><code>template&lt;typename T, size_t N&gt; class Vector : public VectorBase&lt;T, N&gt; { public: Vector(VectorBase&lt;T, N&gt; const &amp;other); }; </code></pre> <p>However, now I'm converting from <code>Vector</code> to <code>VectorBase</code> and back again. Even though the types are the same in memory, and the compiler might optimize all this away, it feels clunky and I don't really like to have potential run-time overhead for what is essentially a compile-time problem.</p> <p>Is there any other way to solve this?</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