我有以下代码,表示 3D 应用程序中的网格(为清楚起见省略了一些代码):
class Mesh {
public:
typedef std::vector<Vertex> Vertices;
typedef std::vector<int> Elements;
template<class VerticesIt, class ElementsIt>
Mesh(const VerticesIt verticesBegin,
const VerticesIt verticesEnd,
const ElementsIt elementsBegin,
const ElementsIt elementsEnd) :
vertices_(verticesBegin, verticesEnd),
elements_(elementsBegin, elementsEnd) {
}
virtual ~Mesh();
typename Vertices::const_iterator verticesBegin() const {
return vertices_.begin();
};
typename Vertices::const_iterator verticesEnd() const {
return vertices_.end();
};
typename Elements::const_iterator elementsBegin() const {
return elements_.begin();
};
typename Elements::const_iterator elementsEnd() const {
return elements_.end();
};
private:
Vertices vertices_;
Elements elements_;
};
它工作得很好,为内部数据提供了一个清晰的界面。没有公开容器的实现细节。
不过,我对此有一点小问题。我不能使用基于范围的 for 循环,必须使用迭代器:
for (auto it = mesh.verticesBegin(); it != mesh.verticesEnd(); ++it) {
// Do stuff
}
for (auto it = mesh.elementsBegin(); it != mesh.elementsEnd(); ++it) {
// Do stuff
}
对我的口味来说有点冗长。我的首选客户端代码将如下所示:
for(auto & vert : mesh.vertices) {
// Do stuff.
}
for(auto & element : mesh.elements) {
// Do stuff.
}
是否可以在不暴露容器的实现细节的情况下实现这一点?另外,我不想将容器包装到自定义类中,因为我希望完全访问 Mesh 类中的所选容器(std::vector)。