> Please see
http://www.open-std.org/JTC1/SC22/WG...005/n1868.html
Thanks, that looks quite promising.
I have one question though - I wonder if it is possible to achieve
similar syntax for containers which do not use the standard begin/end
approach to container enumeration, and for "multi-containers". Here's
an example of both:
struct Vertex;
struct Face;
class IMesh
{
public:
virtual unsigned numVerts() const = 0;
virtual const Vertex& vert( unsigned i ) const = 0;
virtual unsigned numFaces() const = 0;
virtual const Face& face( unsigned i ) const = 0;
};
It is often more intuitive and useful to enumerate a container using
count()/item(i) methods than begin/end. (Am I wrong about this? Would
begin/end work better for the above example too?)
And as you can see above, sometimes we need "multi-containers", i.e.
containers which hold several collections. It would be nice to be able
to write
IMesh& m = ...;
for ( Vertex v : m )
{
....
}
for ( Face f : m )
{
....
}
with the first loop iterating over mesh vertices and the second over
faces, as expected.
Of course, this wouldn't work if the two collections were of the same
type, which could happen easily in the above example if we had:
typedef Vector3 Vertex;
typedef Vector3 Normal;
struct Face;
class IMesh
{
public:
... // same as above
virtual const Normal& vertNormal( unsigned i ) const = 0;
};
In that case we won't be able to write neither "for ( Vertex v : mesh
)", nor "for ( Normal n : mesh )", although a "strong typedef" could
solve the problem (btw, is there a proposal about "strong typedefs" by
any chance? ;) )
Actually, the first "feature request" about foreach supporting
containers of the count()/item(i) style can be achieved with your
current proposal by writing a special iterator like this:
class ItMeshVert
{
public:
ItMeshVert( const IMesh&, unsigned i );
const Vertex& operator*();
bool operator==( const ItMeshVert& other );
private:
const IMesh& mesh_;
unsigned i_;
}
(implementations are obvious), and defining these two:
ItMeshVert begin( const IMesh& m ) { return ItMeshVert( m, 0 ); }
ItMeshVert end( const IMesh& m ) { return ItMeshVert( m, m.numVerts()
); }
(btw, there seems to be a mistake in the "for-loop requirements" part
of your example for item 4 - all four functions are called "begin").
This would require some extra work on behalf of the container designer
(a non-const version of ItMeshVert may be needed if IMesh allows
non-const access to vertices), but it's not too bad.
However, I don't see how the other "feature request" about
multi-containers could be implemented... (the strong typedefs can help,
but in some cases the collection types are exactly the same, not just
aliases of the same type). Actually, I'm not very sure myself if it is
a good idea... it just sounds good :)
Regards,
Ivan
[ See
http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]