Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well, I would have thought that someone would have brought the answer now, however it seems not, so let's go.</p> <p>What you are wishing for is something I have myself dreamed of: a <code>boost::optional_array&lt;T,N&gt;</code>.</p> <p>There are two variants:</p> <ul> <li>First: similar to <code>boost::array&lt; boost::optional&lt;T&gt;, N &gt;</code>, that is each element may or may not be set.</li> <li>Second: similar to a <code>std::vector&lt;T&gt;</code> (somehow), that is all beginning elements are set and all following ones are not.</li> </ul> <p>Given the previous questions / comments, it seems you would like the second, but it doesn't really matter as both are quite alike.</p> <pre><code>template &lt;typename T, size_t N&gt; class stack_vector { public: bool empty() const { return mSize == 0; } size_t size() const { return mSize; } size_t capacity() const { return N; } size_t max_size() const { return N; } T&amp; operator[](size_t i) { return *(this-&gt;pfront() + i); } /// ... private: T* pfront() const { return reinterpret_cast&lt;T*&gt;(&amp;mStorage); } std::aligned_storage&lt; N * sizeof(T), alignof(T) &gt; mStorage; size_t mSize; // indicate how many elements are set, from the beginning }; </code></pre> <p>Let's focus on those very special operations:</p> <pre><code>template &lt;typename T, size_t N&gt; void push_back(T const&amp; t) { new (this-&gt;pfront() + mSize) T(t); // in place construction ++mSize; } template &lt;typename T, size_t N&gt; void clear() { for (size_t i = 0; i != mSize; ++i) { (this-&gt;pfront() + i)-&gt;~T(); } mSize = 0; } </code></pre> <p>As you can notice, the main difficulty is to remember that:</p> <ul> <li>if no element has been built there yet, you need placement new + copy construction instead of assignment.</li> <li>elements that become "obsolete" (ie would be after the last element) should be properly disposed of (ie their destructor be invoked).</li> </ul> <p>There are many operations on traditional STL container that may be tricky to implement. On a <code>vector</code>, element shuffling (due to <code>insert</code> or <code>erase</code>) are perhaps the most stricking examples.</p> <p>Also note that with C++0x and initializer-lists <code>vector</code> get <code>emplace_back</code> to directly construct an element in place, thus lifting the <code>CopyConstructible</code> requirement, might be a nice boon dependent on your case.</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