【发布时间】:2016-01-08 14:44:00
【问题描述】:
在 C++ (STL) 中,我们定义了 const 和 non-const 方法以及两种迭代器,用于在集合上进行迭代:
class Container
{
public:
iterator begin();
const_iterator begin() const;
};
我们如何将这种技术扩展到 D?我的第一次尝试:
class Container(T) {
class Range {
ref T front();
// implementation
}
class ConstRange {
T front() const;
// implementation
}
Range all() {
return new Range(/**/);
}
ConstRange all() const {
return new ConstRange(/**/);
}
}
unittest {
alias list = List!int;
const list L = new list;
writeln(L.all());
}
但是失败了。我有一个错误:
Error: nested type List.List!int.List.Range should have the same or weaker constancy as enclosing type const(List!int)
怎么了?
【问题讨论】:
-
常量迭代器?这甚至是 D 中的东西吗?
-
@sigod,不,但麻烦不在其中)D 中没有“const 范围”,但对 const 容器的迭代必须正常工作,并且方法
front不应返回ref T。即使它不是“D-way” -
std.array.dmakes the range external(请记住private如果在文件/模块级别而不是类级别)