Hey guys,
I was wondering if it's possible to write a generic-but-specialize-able code.
For example, I'm trying to build an iterator for a container. I want it to be bidirectional and I realize that my way of iterating either way in the container has roughly the same structure.
The iterator stores an 'Element' pointer and a 'State' type.
The container stores a vector of unique_ptr's to Elements. Each Element has a State of Default, Alive, Free or Boundary. While iterating, our state will never be Default. While we're either Alive or Free it's safe to treat the iterator's internal pointer as one to contiguous memory (because it's allocated as such [type of pointer is std::unique_ptr<Element<T> []>]). At the boundaries though we need much more special behavior.
Boundary types are Elements who contain a pointer to another Boundary Element on a separate block of memory. This way, the container can allocate its memory in blocks and they can be linked to provide a means of iteration.
The container also stores a copy of the address of the very first element and the very last element, both of which are type Boundary.
I have a step function whose skeleton looks like this:
So, instead of writing StepForward() or StepBackward() functions, how would I be able to get specialized behavior using compile-time constructs? Or is it even possible? I've been trying to approach this using lambdas or something conceptually similar and use a run-time construct.Code:template <class T> void ContainerIterator<T>::Step() { if (state_ == Element<T>::State::Boundary) { if (element_ == container_.first_) { // forward: advance pointer // backward: just return } if (element_ == container_.last_) { // forward: just return // backward: retract pointer } // forward: ++element; // backward: --element; state_ = element_->GetState(); } /* ... */ }