gpt4 book ai didi

c++ - 如何从基类容器中提取派生类?

转载 作者:行者123 更新时间:2023-11-28 01:09:14 26 4
gpt4 key购买 nike

在使用公共(public)父类将不同类型的对象存储在同一个容器中之后,我需要将它们提取回来。

[测试/test0.c++]:

int main()
{
element wrapper;
wrapper.name = "div";
wrapper.attributes["id"] = "wrapper";

cargo<string> text("Learn from yesterday, live for today, hope for tomorrow.");

wrapper.children.push_back(&text);

cout << "Name:\t" << wrapper.name << endl;

/* I have an explicit cast here,
* but it can't be used this way
* since children may have different types
*/
cout << "Cargo:\t" << ((cargo< string >*) wrapper.children[0])->value << endl;

return 0;
}

[来源/element.h]

struct element
{
std::string name;
std::map< std::string, std::string > attributes;
std::vector< node* > children;
};

[源/node.h]

struct node
{ };

[来源/cargo.h]

template <typename Type>
struct cargo
: public node
{
Type value;

cargo(Type value)
: value(value)
{ }
};

我需要某种类型的持有者与真实的节点类型相关联,并在进一步的转换提取操作中使用它......而不是我的测试中的硬编码。

更新:

我正在尝试做的是一个简单的文档对象模型数据结构,将其用作我的类 xml 语言解析器的符号表条目。我不想使用任何现有的 XML 库,因为它们非常大。我认为 DOM 的思想很简单,所以我可以很容易地将它用于一些更复杂的操作,例如,通过使用 cargo<Type> 允许 DOM 树中节点的泛型类型。 .我承认我采用的设计可能不是最合适的!所以我愿意接受建议!

如有任何帮助,我将不胜感激!

最佳答案


这个问题可能更多的是关于设计而不是实现。
尽管 Boost.Variant 和 Boost.Any 可以工作,但它们只是一种变通方法。真正的问题可能是从节点类派生的类的可变责任部分没有被封装。
您可以尝试改用组合。一个用于公共(public)接口(interface)的主机类和适当数量的组件/委托(delegate)/任何东西(那些将诞生于解决方案设计:))。

或者...完全不同的解决方案可能适合您。您可能想冒险使用元编程词并放弃通用接口(interface)。相反,像元组(类型列表)这样的实体可能会有所帮助。

最好的问候,
马尔辛

关于c++ - 如何从基类容器中提取派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4338318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com