如何在派生类上强制派生类成员 [英] How to enforce derived class members on derived classes
问题描述
如何强制派生类具有特定派生类型的成员数据.
How does one enforce a derived class to have member data of a specific derived type.
即
class Project {
public:
int projdata;
};
class Article: public Project {
};
class Building: public Project {
};
class Emplooyee {
public:
std::vector<Project> projs;
}
class Architect: public Employee {
};
class Writer: public Employee {
};
我现在如何强制Architect对象仅具有Building类型的项目,而Novelist仅具有Article类型的项目?即,我想要类似的东西
How do I now enforce that Architect objects only have projects of type Building, while Novelist only have projects of type Article? i.e., I want to have something like
class Architect: public Employee {
public:
std::vector<Building> projs;
};
和
class Novelist: public Employee {
public:
std::vector<Article> projs;
};
我还可以存储指向项目的指针,然后将其转换为正确的类型.是否有一种技术或设计模式可以在派生类的成员上强制执行此类相应的继承规则?
I could also store pointers to projects and then store cast them into the correct type. Is there a technique or design pattern to enforce such corresponding inheritance rules on members of derived classes?
推荐答案
一种编译时的解决方案是使基础成为模板:
A compile time solution is to make the base a template:
template<class Proj>
class Emplooyee {
public:
std::vector<Proj> projs;
}
class Architect: public Employee<Building> {};
class Writer: public Employee<Article> {};
此外,您可以添加一个其他的非模板库,以使Architect
和Writer
属于同一层次结构,但是该非模板库不能处理projs
成员.
Additionally, you can add a one additional non-template base so that Architect
and Writer
are part of same hierarchy, but that non-template base cannot deal with the projs
member.
如果模板不是选项,则必须依靠运行时检查.为此,Project
必须是多态类型,并且必须使用typeid
或dynamic_cast
来强制不变量.并且您必须首先使用间接存储Project
. std::vector<Project>
无法存储任何Building
或Article
对象,因为它仅存储Project
个对象
If a template not an option, then you must rely on runtime checks. For that, Project
must be a polymorphic type, and you must use typeid
or dynamic_cast
, to enforce the invariant. And you must use indirection to store the Project
's in the first place. std::vector<Project>
cannot store any Building
nor Article
objects because it only stores Project
objects only
这篇关于如何在派生类上强制派生类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!