I maintain a container class with an interface similar to std::map / std::unordered_map .
The interface claims that it stores std::pair<const X,Y> (i.e. that value_type ). However, in the internal implementation, the implementation saves the sorted array std::pair<X,Y> .
The current implementation uses reinterpret_cast to implement iterators. My question is, is there a better alternative?
Moving to std::pair<const X,Y> to store the array would be impossible, since for implementation it is necessary to copy the elements in the array to implement insertion and deletion. One way this is done is to use std::sort .
Edit: Although I believe that reinterpret_cast causes undefined behavior (or a specific implementation?), I have yet to meet a compiler where this does not work - am I worried about anything?
Current implementation of iterator dereferencing:
template <class K, class M> std::pair<const K,M>& operator*() { std::pair<K,M>& result = ...; return *reinterpret_cast<std::pair<const K,M>*)(&result); }
source share