Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's something I came up with when playing with C++0x features a while back. The only C++0x feature used in this is <code>static_assert</code>, so you could use Boost to replace that.</p> <p>Basically, we can use a static size check function that just checks to be sure a given index is less than the size of the vector. We use a static assert to generate a compiler error if the index is out of bounds:</p> <pre><code>template &lt;std::size_t Index&gt; void size_check_lt() const { static_assert(Index &lt; N, "the index is not within the range of the vector"); } </code></pre> <p>Then we can provide a <code>get()</code> method that returns a reference to the element at a given index (obviously a const overload would be useful too):</p> <pre><code>template &lt;std::size_t Index&gt; T&amp; get() { size_check_lt&lt;Index&gt;(); return data_[Index]; } </code></pre> <p>Then we can write simple accessors like so:</p> <pre><code>T&amp; x() { return get&lt;0&gt;(); } T&amp; y() { return get&lt;1&gt;(); } T&amp; z() { return get&lt;2&gt;(); } </code></pre> <p>If the vector has only two elements, you can use x and y but not z. If the vector has three or more elements you can use all three.</p> <p>I ended up doing the same thing for constructors--I created constructors for vectors of dimension two, three, and four and added a <code>size_check_eq</code> that allowed them to be instantiated only for vectors of dimension two, three, and four, respectively. I can try and post the complete code when I get home tonight, if anyone is interested.</p> <p>I dropped the project halfway through, so there might be some huge problem with doing it this way that I didn't run into... at least it's an option to consider.</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