Address of the pointed element whatever the iterator type/pointer is passed

Vincent picture Vincent · Aug 29, 2012 · Viewed 23.6k times · Source

What would be the most generic syntax for the following function :

template<IteratorType> void myFunction(const IteratorType& myIterator)
{
    _ptr = &myIterator[0];
}

It take an iterator myIterator (it can be a raw pointer) and the goal is to assign the address of the object pointed by myIterator to a raw pointer _ptr. Currently I use &myIterator[0] but I realized that only random access iterators have the operator [].

So is there a syntax that will work with all type of standard iterators and pointers ?

Answer

ForEveR picture ForEveR · Aug 29, 2012

You can dereference pointer and then take address of object.

template<IteratorType> void myFunction(const IteratorType& myIterator)
{
    _ptr = &(*myIterator);
}