Christopher Diggins在他的blog文章introducing the Iterable Concept中提到了迭代的概念,且看他的定义的实例:
In pseudo-C++ this translates to roughly:
concept Iterable {
public {
typedef value_type;
template<typename Procedure>
void for_each(Procedure proc);
}
}
Example 1: Outputting all Elements from an Iterable
struct putter {
putter(std::ostream& o, char delim = ' ') : out(x) { }
template<typename T> void operator()(T& x) {
out << x << delim;
}
std::ostream& out;
};
putter put(std::ostream& o) {
return putter(o);
}
template<typename Iterable>
void print_iterable(Iterable& i) {
i.for_each(put(std::cout));
}
Example 2: Concatenation of Iterable Collections
It is easy to concatenate two completely different Iterable collections, to create a new type which can be used whereever a Iterable is called for.
template<typename Iterable1, typename Iterable2>
struct cat {
cat(Iterable1& i1, Iterable2& i2)
: iterable1(i1), iterable2(i2)
{ }
template<typename Procedure>
void for_each(Procedure proc) {
iterable1.for_each(proc);
iterable2.for_each(proc);
}
typedef typename Iterable1::value_type value_type;
Iterable1& iterable1;
Iterable2& iterable2;
};
Example 3: Adapting a Container to an Iterable
Any class modeling a Container concept, can be trivially converted to an Iterable concept:
template<typename Container>
struct container_to_iterable {
container_to_iterable(Container& x) :
container(x)
{ }
template<typename Procedure>
for_each(Procedure p) {
typename Container::iterator iter = container.begin();
typename Container::iterator last = container.end();
while (iter != last) {
p(*iter++);
}
}
Container& container;
}
常规的迭代器概念是从数据(指针)的角度定义的,属于单体;而这里的定义是从操作(遍历)的角度定义,属于整体。(这里的Procedure是一个函数对象,类似于C#的delegate)。
思维比较新颖。