C ++-抽象类的迭代器 [英] c++ - an iterator for an abstract class

查看:104
本文介绍了C ++-抽象类的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类,例如一个代表几何形状的类。我将有从 Shape 继承的具体类,例如矩形和三角形。

I have an abstract class, for example a class the represents a geometrical shape. I will have concrete classes inheriting from Shape, such as a rectangle and a triangle.

我想遍历形状所组成的点(另一类),所以必须提供 Shape 一个接口。
迭代应采用以下方式:

I would like to iterate over the points (another class) a shape is composed of, so Shape must supply an interface for it. The iteration should be in this manner:

for(Point p : shapeObject){ ... some code}

但是我不希望 Shape 类为子类确定要使用的容器。例如,矩形将具有 std :: array< Point,4> 容器,而三角形将具有 std :: array< Point, 3> 容器。

But I don't want the Shape class to determine for the child class what containers to use. For example, a rectangle will have a std::array<Point, 4> container while a triangle will have a std::array<Point, 3> container.

所以我的问题是,最优雅的C ++方式是什么?

So my question here is, what is the most elegant C++ way to do this?

推荐答案

在点存储在支持随机访问迭代的容器中的特定情况下,解决问题的简单方法 * (例如 std :: array std :: vector 是将普通指针用作迭代器:

A simple way to solve the "problem"* in the particular case where the points are stored in containers supporting random access iteration (such as std::array or std::vector is to use plain pointers as iterators:

struct Point {};

struct Shape
{
    typedef Point* iterator;
    typedef const Point* const_iterator;
    virtual iterator begin() = 0;
    virtual const_iterator begin() const = 0;
    virtual iterator end() = 0;
    virtual const_iterator end() const = 0;
    virtual ~Shape() {}
};

并让派生类实现 begin() end()使用指向它们所持有数组的第一个和最后一个结束元素的指针。

And have the derived classes implement begin(), end() using pointers to the first and past the end elements of the array they hold.

或者,您可以将类型擦除与例如 boost.any_range 或通过 any_iterator 类型。这可能超出了此答案的范围,但是这里是一篇有关此问题的好文章

Alternatively, you could use type-erasure with e.g. boost.any_range or via an any_iterator type. This may be beyond the scope of this answer but here is a good article on precisely this problem.

**这是假设确实存在一个问题,需要隐藏迭代器的类型。请注意,您还可以编写模板代码来处理不同的迭代器类型。

这篇关于C ++-抽象类的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆