Address of the pointed element whatever the iterator type/pointer is passed
-
29-06-2021 - |
문제
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 ?
해결책
You can dereference pointer and then take address of object.
template<IteratorType> void myFunction(const IteratorType& myIterator)
{
_ptr = &(*myIterator);
}
다른 팁
According to standard * operator return a reference so in my opinion the best way is &*myIterator
, but since the class may overloaded the & operator the best way is std::addressof(*myIterator)
that work for all classes
All iterators are required to have operator *
(24.2.2:2), so you can write
_ptr = &*myIterator;
However, this is not valid for output iterators, where *r
is only valid on the left hand side of an assignment operation (24.2.4:2).
Also note that it is not necessarily true that *r
will provide a value that &
can sensibly be applied to; the specialization std::vector<bool>
(23.3.7) has a reference
type that is not bool &
, for example. In your case the assignment _ptr = &*myIterator
would catch this, assuming that _ptr
is an appropriate pointer type, and you would get a compile failure.
I hope you guys are all alive right now. If your iterator is an iterator for std::vector
, there is a nicer way to get the address that the iterator is holding. You can use:
auto *ptr = myIterator._Ptr;
I hope I could give a proper answer to your question.