我有一个抽象类,例如代表几何形状的类。我将有继承自的具体类Shape
,例如矩形和三角形。
我想迭代形状组成的点(另一个类),所以Shape
必须为其提供一个接口。
迭代应该是这样的:
for(Point p : shapeObject){ ... some code}
但我不想要Shape
class 来确定子类要使用哪些容器。例如,一个矩形将有一个std::array<Point, 4>
容器,而三角形将有一个std::array<Point, 3>
容器。
所以我的问题是,最优雅的 C++ 方法是什么?
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()
使用指向它们所保存的数组的第一个和最后一个元素的指针。
或者,您可以使用类型擦除,例如boost.any_range http://www.boost.org/doc/libs/1_54_0/libs/range/doc/html/range/reference/ranges/any_range.html或通过any_iterator
类型。这可能超出了这个答案的范围,但是这是一篇关于这个问题的好文章 http://thbecker.net/free_software_utilities/type_erasure_for_cpp_iterators/any_iterator.html.
* That is assuming there really is a problem that requires hiding the type of the iterators. Note that you can also write template code to deal with different iterator types.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)