Search code examples
c++pointersiteratorobject-address

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


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 ?


Solution

  • You can dereference pointer and then take address of object.

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