[Solved] Making container 'foreach'able: Conversion loses qualifiers
-
I have a custom container that I want to make iterable. Specifically, the following code should compile:
@
// Note: We are inside a non-const method
CTpeb_ElementMap selectedSiblings = getSelectedSiblingElements();Q_FOREACH(CTpeb_AbstractElement* pElement, selectedSiblings)
{
// ...
}
@Withing my ElementMap class, I have the iterator class defined (I'm leaving out const_iterator for the moment):
@ class iterator
{
public:
typedef std::forward_iterator_tag iterator_category;iterator(); iterator(const iterator& other); iterator& operator=(const iterator& other); CTpeb_AbstractElement*& operator*() const; bool operator==(const iterator& other) const; bool operator!=(const iterator& other) const; iterator& operator++(); private: // ... };@
In CTpeb_ElementMap, I have the begin() and end() methods:
@
CTpeb_ElementMap::iterator begin();
CTpeb_ElementMap::iterator end();
@The error message is:
bq. cannot convert from 'const CTpeb_AbstractElement *' to 'CTpeb_AbstractElement *' - Conversion loses qualifiersCurrently, I have removed all the interfaces allowing access to a const_iterator. Why does Q_FOREACH still manage to access a 'const CTpeb_AbstractElement*' ? Any ideas?
EDIT:
When I expand Q_FOREACH into a looper over the iterator, it compiles:
@ for(CTpeb_ElementMap::iterator iter = selectedSiblings.begin(); iter != selectedSiblings.end(); ++iter)
{
CTpeb_AbstractElement* pElement = *iter;
// ...
}@What's the difference between my loop and a standard Q_FOREACH loop?
EDIT2: Solution:
I realized that Q_FOREACH always uses the const_iterator. In my case, the const_iterator must return a byvalue copy of the pointer - the pointer itself can thus not be changed (which satisfies the const_iterator's const correctness), but the object behind the pointer can be changed (which is what I intended within my foreach loop).