mercredi 26 août 2015

c++ foreach loop with pointers instead of references

I have this Container class with begin() and end() functions for use with c++11 foreach loops:

class Element
{
    //content doesn't matter
};

class Container
{
    Element* elements;
    int size;

    /* constructor, destructor, operators, methods, etc.. */

    Element* begin() { return elements; };
    Element* end()   { return elements + size; };
};

This is now a valid c++11 foreach loop:

Container container;
for (Element& e : container)
{
    //do something
}

But now consider this foreach loop:

Container container;
for (Element* e : container)
{
    //do something
}

Is it possible to have a foreach loop with Element* instead of Element& like this?
This would also have the grreat advantage of preventing one from typeing for (Element e : container) which would copy the element each time.

In that case begin() and end() would have to return Element** as far as I know.

But sizeof(Element) is not guaranteed to be sizeof(Element*) and in most cases they don't match. Incrementing a pointer increments by the base type size which is sizeof(Element) for incrementing Element* and sizeof(Element*) for incrementing Element**.

So the prefix operator++() will offset the pointer by a false value and things get crappy. Any ideas how to get this to work?

Aucun commentaire:

Enregistrer un commentaire