【发布时间】:2015-04-29 07:24:23
【问题描述】:
我的情况如下:
#include <set>
#include <map>
#include <vector>
#include <string>
class BaseCollection {
// I don't know what to keep here
// I want to have access to collection elements
// seems I need to implmement begin(), end() for collections
};
class CollectionA : public BaseCollection {
public: // in real code this will be private
std::vector<double> coll_;
};
class CollectionB : public BaseCollection {
public: // in real code this will be private
std::set<double> coll_;
};
class CollectionC : public BaseCollection {
public: // in real code this will be private
std::map<std::string, double> coll_;
};
class Base {
public:
virtual BaseCollection* getColl() = 0;
};
class A : public Base {
virtual BaseCollection* getColl() { return &coll_; }
public: // in real code this will be private
CollectionA coll_;
};
class B : public Base {
virtual BaseCollection* getColl() { return &coll_; }
public: // in real code this will be private
CollectionB coll_;
};
class C : public Base {
virtual BaseCollection* getColl() { return &coll_; }
public: // in real code this will be private
CollectionC coll_;
};
class Container {
public:
typedef std::map<std::string, Base*>::const_iterator const_iterator;
Container::const_iterator begin() const { return objects_.begin(); }
public: // in real code this will be private
std::map<std::string, Base*> objects_;
};
int main() {
// somewhere we're creating objects of different types and filling their collections
A objA;
// suppose we filled objA.coll_ somehow
Base* ptrA = new A;
ptrA = &objA;
// somwhere we're iterationg over Container
Container c;
c.objects_["objA"] = ptrA;
Container::const_iterator itBeg = c.begin();
BaseCollection* coll = itBeg->second->getColl();
// and here I want to itarate over collection
}
所以,我需要以某种方式至少为BaseCollection 定义begin()、end() 并在派生类中实现它们。
或者也许我需要使用模板?但我想不通。
我该怎么做?
或者这不可能,我需要为每种类型保留单独的容器(A、B、C)。
编辑:
所以,我拥有的是一个Base 类,以及一些从它派生的类(A、B、C),它们包含不同类型的集合。实际上我想要的是Base 中的一个接口来迭代它当前指向的派生类的集合。
提前致谢。
【问题讨论】:
-
您能否详细说明您的目标是什么?你想要的是一个元素的集合,其中所有元素都是 A 型、B 型或 C 型?您希望能够单独访问它们作为类型 A 还是仅作为基本类型?
-
@laurisvr,是的,集合中的元素是 A 型、B 型或 C 型,我希望能够将它们作为基本类型访问。
-
你有为集合使用多个子类吗?你不能简单地使用一个模板化的
Collection类并在你的A、B和C类中使用它吗?而且我真的不明白A、B和C具有共同祖先类的原因,您能否尝试解释一下您的用例?您实际上要解决什么问题? (您可能想了解the XY problem。) -
@JoachimPileborg,如果我有一个模板化的
Collection类,那么我的 Base 类也将被模板化,但我希望它不是模板。我将编辑我的问题并编写实际问题。 -
我已经回答了一个与您的here 非常相似的问题。
标签: c++ templates inheritance