I think it is easier to just show this in code:
#include <iostream>
#include <array>
struct Test
{};
int main()
{
std::array<Test, 1> arr {};
Test* t = arr.begin();
}
arr.begin() returns a iterator but as you can see I can refer to it with Test*. This seems to be possible due to implicit cast, can I expect this to work across other compilers as well according to the standard?
Also is it the operator TYPE that does the implicit cast, ex:
operator T*()
{
return &(*this->CONTAINER)[index];
}
template <typename U>
operator U() = delete;
or something else?
Thanks in advance
std::array::begin returns an iterator, not a pointer.
The iterator can be defined as a pointer, but it doesn't need to be.
To get a pointer to first item you can use std::array::data.
Re the “implicit cast”, no, there's no such here.
A general technique for converting an iterator to raw pointer is to first derefence it, *it, which generally yields a reference, and then take the address of that, &*it. However, this will necessarily fail when there is no addressable item to take the address of, such as in a packed std::vector<bool> (it's up to the implementation whether it's packed, but if it's packed). In such a case dereferencing the iterator yields some proxy object instead of a raw reference.
As seen in The C++ standard draft an iterator is implementation-defined:
using iterator = implementation-defined; // see [container.requirements]
[container.requirements] says that iterator should be at least:
Any iterator category that meets the forward iterator requirements. convertible to X::const_iterator.
Neither requirements of a forward iterator nor the requirements of the InputIterator (ForwardIterator needs to satisfy requirements for InputIterator) nor the requirements of an Iterator (InputIterator needs to satisfy requirements for Iterator) state that they should have this conversion operator and thus this is very compiler specific and not standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With