【发布时间】:2015-08-11 14:13:54
【问题描述】:
我有一个接口 ICollection 实现了一个集合 ArdalanCollection,如下所示:
template <typename T>
class ICollection
{
public:
virtual void add(T*) = 0;
virtual T* get(int) = 0;
virtual int count() = 0;
};
template <typename T>
class ArdalanCollection :public ICollection<T>
{
public:
ArdalanCollection() {
index = 0;
};
virtual void add(T* obj) {
encapsolateImplementation.insert(make_pair(index++, obj));
};
virtual T* get(int index) {
return encapsolateImplementation[index];
};
virtual int count() {
return encapsolateImplementation.size();
};
private:
int index;
unordered_map < int, T* > encapsolateImplementation;
};
我想要的是在 ICollection 接口中有一个通用迭代器,它可以循环所有内部容器元素(我还没有决定选择 unordered_map 作为我的内部容器,我可能会将其更改为 boost或者是其他东西)。我想以这种方式使用它:
Node *node1 = new Node(1, 0, 0, 0);
Node *node2 = new Node(1, 0, 0, 0);
ICollection<Node> *nodes = new ArdalanCollection<Node>();
nodes->add(node1);
nodes->add(node2);
for (it=nodes->iterator.begin(); it < nodes->iterator.end(); it++) {
}
【问题讨论】:
-
将模板与虚函数混合使用是代码异味。
-
与论坛网站不同,我们不使用“谢谢”、“任何帮助表示赞赏”或Stack Overflow 上的签名。请参阅“Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?。顺便说一句,这是“提前致谢”,而不是“致谢”。
标签: c++ interface iterator generic-programming